Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

php - Object could not be converted to string?

Why am I getting this error:

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

Here is the code:

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

(Line 79 is the $query and the function is part of class Card)

All the declarations of Card:

public $type;

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

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

After changing line 79 to this:

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

I now get this error:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Read about string parsing, you have to enclose the variables with brackets {}:

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

Whenever you want to access multidimensional arrays or properties of a property in string, you have to enclose this access with {}. Otherwise PHP will only parse the variable up to the first [i] or ->property.

So with "$this->author->last" instead of "{$this->author->last}", PHP will only parse and evaluate $this->author which gives you the error as author is an object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...