phpstringobjectsshssh2-exec

How to convert object class into string


How can I convert the following object into string:

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

So I can parse the string as the first parameter in 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
}

As currently when I run my script I get the following error message:

strpos() expects parameter 1 to be string

I've seen similar questions including this one Object of class stdClass could not be converted to string , however I still can't seem to come up with a solution.


Solution

  • There are two problems with this line of code:

    if($idx = strripos($ssh,','))
    
    1. $ssh is an instance of some class. You use it above as $ssh->exec(...). You should check the value it returns (probably a string) and strripos() on it, not on $ssh.

    2. strripos() returns FALSE if it cannot find the substring or a number (that can be 0) when it founds it. But in boolean context, 0 is the same as false. This means this code cannot tell apart the cases when the comma (,) is found as the first character of the string or it is not found at all.

    Assuming $ssh->exec() returns the output of the remote command as string, the correct way to write this code is:

    $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
    }
    

    There is no need to use strripos(). It performs case-insensitive comparison but you are searching for a character that is not a letter, consequently the case-sensitivity doesn't make any sense for it.

    You can use strrpos() instead, it produces the same result and it's a little bit faster than strripos().


    An alternative way

    An alternative way to get the same outcome is to use explode() to split $output in pieces (separated by comma) and get the last piece (using end() or array_pop()) as the error code:

    $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
    }
    

    This is not necessarily a better way to do it. It is, however, more readable and more idiomatic to PHP (the code that uses strrpos() and substr() resembles more the C code).