2010-07-08 160 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()方法定義,所以它不能被表示爲字符串。