【问题标题】:Object could not be converted to string?对象无法转换为字符串?
【发布时间】:2010-07-08 05:37:33
【问题描述】:

为什么会出现这个错误:

可捕获的致命错误: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 行是 $query,该函数是 Card 类的一部分)

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')";

我现在收到此错误:

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

【问题讨论】:

  • 那是因为$this-$author->qualifications

标签: php


【解决方案1】:

阅读string parsing,您必须用括号将变量括起来{}

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

当您想要访问多维数组或字符串中的属性时,您必须用{} 将此访问权限括起来。否则 PHP 只会将变量解析到 first [i]->property

因此,使用"$this->author->last" 而不是"{$this->author->last}",PHP 只会解析和评估$this->author,这会给您带来错误,因为author 是一个对象。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      访问属性名称时不应将 $ 放在它们之前:

      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);
          }
      

      【讨论】:

        【解决方案4】:

        您正在尝试回显对象本身,而不是它的字符串属性。仔细检查您的代码。

        【讨论】:

          【解决方案5】:

          你可能想使用:

          $query = "INSERT INTO cards VALUES('$this->type','$this->tag' // etc
          

          【讨论】:

            【解决方案6】:

            我认为其中一个对象没有定义 toString() 方法,因此它不能表示为字符串。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2013-06-28
              • 2019-12-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多