PHP 问题:打印对象
问题
执行了以下代码。
这产生了以下错误。
Catchable fatal error: Object of class MyClass could not be converted to string intest.phpon line 7 Call Stack: 0.0011 323736 1. {main}() /test.php:0如何简单地更改代码以防止此错误并产生某种形式的结果?
回答
重写此代码并实际正确打印出对象的最简单方法是使用__toString()魔术方法。这个方法必须返回一个字符串并被自动调用一个对象被打印出来。因此,示例代码可以这样重写:
foo; } } $myObject = new MyClass(); echo $myObject;这会阻止错误发生,并将产生以下输出。
bar
该__toString()函数既可用于调试目的,也可用于装饰输出。例如,我们可以有一个User类来打印用户的信息,还有一个HtmlUser装饰器类,用周围的HTML标签打印出用户的信息。这将是这样写的:
_username = 'user1'; $this->_forename = 'John'; $this->_surname = 'Doe'; $this->_created = time(); } public function __toString() { $output = ''; $output .= "Username = " . $this->_username . "\n"; $output .= "Forename = " . $this->_forename . "\n"; $output .= "Surname = " . $this->_surname . "\n"; $output .= "Created = " . $this->_created . "\n"; return $output; } } class HtmlUser { protected $user; public function __construct(User $user) { $this->user = $user; } public function __toString() { $output = "
- \n";
$output .= "\t
- Username " . $this->user->_username . " \n"; $output .= "\t
- Forename " . $this->user->_forename . " \n"; $output .= "\t
- Surname " . $this->user->_surname . " \n"; $output .= "\t
- Created " . $this->user->_created . " \n"; $output .= "
这会产生以下输出:
- Username user1
- Forename John
- Surname Doe
- Created 1304196043