无法打印标准类属性



在下面的示例中,我尝试在另一个字符串(查询)中打印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
$str = "INSERT INTO [...] VALUES ('$db_items->cover->file_already_exists')";

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

使用字符串串联

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

或复杂(卷曲)语法,

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

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

最新更新