PHP5引入的一个新的功能是类的 __toString()方法。
在5.2之前PHP会把对象解析成一个字符串来输出
5.2以后会报错。
通过在类中定义__toString()方法,就可以控制字符串的输出,这样当对象被echo 或
<?php
error_reporting(E_ALL);
class person {
public $name;
public $age;
public function __construct($name,$age){
$this->name = $name;
$this->age = $age;
}
public function __toString(){
return 'Object info name:'.$this->name.' age:'.$this->age;
}
public function __destruct(){
}
$person = new person('Zhangsan','20');
echo $person
者print的时候会调用__toString()方法。
本文转自kefirking 51CTO博客,原文链接:http://blog.51cto.com/phpzf/804722,如需转载请自行联系原作者