无法打印stdClass属性

时间:2016-06-10 23:49:00

标签: php string object

在下面的示例中,我尝试在另一个字符串(一个查询)中打印file_already_exists,但是我收到此错误:

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;

使用$db_items->file_already_exists正常,但不是$db_items->cover->file_already_exists。这是为什么?有没有办法打印cover中的那个?

以更简单的方式

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

1 个答案:

答案 0 :(得分:0)

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

解析器不知道变量名称的结束位置,因此它会尝试将$db_items插入到字符串中 - 这会导致转换问题。

使用字符串连接

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

complex (curly) syntax

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

根据值的来源,不要忽视SQL注入!