如何将对象类转换为字符串

时间:2018-04-03 09:20:14

标签: php string object ssh ssh2-exec

如何将以下对象转换为字符串:

$ssh->exec('tail -1 /var/log/playlog.csv');

所以我可以将字符串解析为strripos()中的第一个参数:

if($idx = strripos($ssh,','))//Get the last index of ',' substring 
{
$ErrorCode = substr($ssh,$idx + 1,(strlen($ssh) - $idx) - 1); //using the found index, get the error code using substring
echo " " .$Playlist.ReturnError($ErrorCode); //The ReturnError function just replaces the error code with a custom error
}

目前,当我运行脚本时,收到以下错误消息:

strpos() expects parameter 1 to be string

我已经看过类似的问题,包括Object of class stdClass could not be converted to string这个问题,但我似乎无法提出解决方案。

1 个答案:

答案 0 :(得分:0)

这行代码存在两个问题:

if($idx = strripos($ssh,','))
  1. $ssh是某个类的实例。您将上面的内容用作$ssh->exec(...)。你应该检查它返回的值(可能是一个字符串)和strripos(),而不是$ssh

  2. strripos()如果找不到子字符串或数字(可以是FALSE),则会返回0。但在布尔上下文中,0false相同。这意味着当逗号(,)被发现为字符串的第一个字符或根本找不到它时,此代码无法区分这些情况。

  3. 假设$ssh->exec()以字符串形式返回远程命令的输出,编写此代码的正确方法是:

    $output = $ssh->exec('tail -1 /var/log/playlog.csv');
    
    $idx = strrpos($output, ',');        //Get the last index of ',' substring 
    if ($idx !== FALSE) {
        // The value after the last comma is the error code
        $ErrorCode = substr($output, $idx + 1);
        echo ' ', $Playlist, ReturnError($ErrorCode);
    } else {
       // Do something else when it doesn't contain a comma
    }
    

    无需使用strripos()。它执行不区分大小写的比较,但是您正在搜索不是字母的字符,因此区分大小写对它没有任何意义。

    您可以使用strrpos(),它会产生相同的结果,并且比strripos()快一点。

    另一种方式

    获得相同结果的另一种方法是使用explode()$output分成几部分(以逗号分隔)并获取最后一部分(使用end()或{{3} })作为错误代码:

    $output = $ssh->exec('tail -1 /var/log/playlog.csv');
    
    $pieces = explode(',', $output);
    if (count($pieces) > 1) {
        $ErrorCode = (int)end($pieces);
        echo ' ', $Playlist, ReturnError($ErrorCode);
    } else {
       // Do something else when it doesn't contain a comma
    }
    

    这不一定是更好的方法。然而,它对PHP更具可读性和更具惯用性(使用strrpos()substr()的代码更像C代码。)