2010-07-08 125 views
13

为什么我收到此错误:对象无法转换为字符串?

Catchable fatal error: Object of class Card could not be converted to string in /f5/debate/public/Card.php on line 79

这里是代码:

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

现在我得到这个错误:

Catchable fatal error: Object of class Author could not be converted to string in /f5/debate/public/Card.php on line 79

+0

这是因为'$ this- $ author-> qualifications' – quantumSoup 2010-07-08 05:51:35

回答

9

阅读string parsing,你有括号{}围住变量:

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

每当你想访问多维数组或字符串的属性的属性,则必须在其与{}此访问。否则,PHP将只解析变量,最多为第一个[i]->property

因此,与"$this->author->last"代替"{$this->author->last}",PHP只解析和评价$this->author,让你的错误作为author是一个对象。

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

您试图回显一个对象本身,而不是它的字符串属性。仔细检查你的代码。

2

你可能想使用:

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

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

1

我想一个对象没有toString()方法定义,所以它不能被表示为字符串。