php-_toString()方法

php提供了一个叫_toString()的函数,可以用来返回表示对象的字符串信息,一旦定义,打印命令将调用它并打印出返回的字符串。

<?php
class Person{
  function __construct($name){
    $this->name=$name;
  }
  function __toString(){
    return $this->name;
  }
  private $name;
}
$obj=new Person("Andi Gutmans");
echo $obj;
echo '<br>';
print $obj;
?>

结果:

Andi Gutmans

Andi Gutmans

 

posted @ 2017-02-20 20:20  Arya.cc  阅读(1203)  评论(0编辑  收藏  举报