对象无法转换为字符串?

php
2022-08-30 22:12:31

为什么我会收到此错误:

可捕获的致命错误:类 Card 的对象无法转换为第 79 行 /f5/debate/public/Card.php 中的字符串

代码如下:

public function insert()
{
    $mysql = new DB(debate);

    $this->initializeInsert();

    $query = "INSERT INTO cards
            VALUES('$this->$type','$this->$tag','$this->$author->$last','$this->$author->$first',
            '$this->$author->$qualifications','$this->$date->$year','$this->$date->$month',
            '$this->$date->$day','$this->$title', '$this->$source', '$this->$text')";
            $mysql->execute($query);
}

(第 79 行是 函数是类的一部分$queryCard)

所有声明:Card

public $type;

public $tag;
public $title;
public $source;
public $text;

public function __construct() {
    $this->date = new Date;
    $this->author = new Author;
}

将第 79 行更改为以下行后:

$query = "INSERT INTO cards
    VALUES('$this->type','$this->tag','$this->author->last','$this->author->first',
    '$this-$author->qualifications','$this->date->year','$this->date->month','$this->date->day',
    '$this->title', '$this->source', '$this->text')";

我现在得到这个错误:

可捕获的致命错误:类作者的对象无法转换为 /f5/debate/public/Card.php 第 79 行中的字符串


答案 1

阅读有关字符串解析的信息,您必须用括号将变量括起来:{}

$query = "INSERT INTO cards VALUES('$this->type','$this->tag','{$this->author->last}',"

每当要访问字符串中属性的多维数组或属性时,都必须用 .否则,PHP 将只解析变量到第一个 或 。{}[i]->property

因此,PHP 将只解析和评估,而不是 ,这会给你一个对象的错误。"$this->author->last""{$this->author->last}"$this->authorauthor


答案 2

我认为在使用箭头运算符时不需要$ 符号。


推荐