akinuri akinuri - 4 months ago 6x
PHP Question

Can't print stdClass property

In the following example, I'm trying to print

inside another string, a query, but I get this error:

Catchable fatal error: Object of class stdClass could not be converted to string in ...

$db_items = (object) [
"cover" => (object) [
"file_already_exists" => 0, // can't print
"file_already_exists" => 0, // can print

$str = "INSERT INTO albums (file_on_system) VALUES ('$db_items->cover->file_already_exists')";

echo $str;

works fine, but not
. Why is that? Is there a way to print the one in

In a simpler way

echo "$db_items->file_already_exists"; // works
echo "$db_items->cover->file_already_exists"; // doesn't work

$str = "INSERT INTO [...] VALUES ('$db_items->cover->file_already_exists')";

The parser does not know where the variable name ends, so it tries to insert $db_items into the string - and that causes the conversion issue.

Either use string concatenation

$str = "INSERT INTO albums [...] VALUES ('".$db_items->cover->file_already_exists."')";

or the complex (curly) syntax,

$str = "INSERT INTO albums [...] VALUES ('{$db_items->cover->file_already_exists}')";

Depending on where that value originates, do not neglect SQL injection!