PHP输出Book对象触发致命错误:Object of class Book could not be converted to string
解决方法
PHP中使用echo输出自定义对象时,必须让类实现**__toString()魔术方法**,该方法负责返回一个可以表示对象的字符串内容,否则PHP无法自动将对象转换为字符串,就会触发你遇到的致命错误。
修改后的完整代码
<?php class Book{ var $title; var $author; var $pages; var $price; function __construct($a_title , $a_author , $a_pages , $a_price){ $this->title = $a_title; $this->author = $a_author; $this->pages = $a_pages; $this->price = $a_price; } // 实现__toString()魔术方法,定义对象转字符串的规则 function __toString(){ return "书名:{$this->title}<br>作者:{$this->author}<br>页数:{$this->pages}<br>价格:{$this->price}<hr>"; } } $book1 = new Book("One Day The Life will be End","Muhammad Mujtaba",400,32500); $book2 = new Book("A Horse Man In The Sky","Ali Hassan",550,2000); echo $book1; echo $book2; ?>
关键说明
__toString()是PHP内置的魔术方法,当尝试用echo/print输出对象时会自动调用- 你可以根据需求自定义返回内容的格式,比如换成纯文本换行、JSON格式等,只要确保返回的是字符串类型即可
内容的提问来源于stack exchange,提问作者Muhammad Mujtaba
相关产品推荐
相关产品推荐

