Object of class %s could not be converted to string¶
Description¶
PHP reports that the object cannot be used as a string. Converting an object into a string is only possible when the magic method __toString()
is implemented, or when the interface Stringable
is implemented.
In that case, the object is automatically converted into a string, thanks to that method. Otherwise, it is a Fatal error.
This is a distinct error than passing an object in a string argument: in that case, it is a Type error.
A lot of native PHP classes support the conversion, but not all of them. Check for stringable
interface before using them.
Example¶
<?php
class Y { }
//error!
echo (new Y);
// X could also be implementing Stringable, to enforce the __toString() method
class X {
function __construct(array $arg) {
$this->a = $arg;
}
function __toString(){
return implode(', ', $this->arg);
}
}
// valid
echo (new X);
$array1 = [E::A];
$array2 = [E::B];
enum E: string {
case A = 'a';
case B = 'b';
}
// hidden necessary string conversion
array_intersect($array1, $array2); // also with other array_intersect* functions
?>
Literal Examples¶
Object of class Y could not be converted to string
Object of class stdClass could not be converted to string
Solutions¶
Implement the
Stringable
interface on the class, or its parent.Implement the
__toString
method n the class, or its parent.Call a method that returns a string, on that object.
Use
print_r
orvar_dump
to get the details inside the object.