PHP5中定义对象的字符串值

简介:

PHP5引入的一个新的功能是类的 __toString()方法。

在5.2之前PHP会把对象解析成一个字符串来输出

5.2以后会报错。

通过在类中定义__toString()方法,就可以控制字符串的输出,这样当对象被echo 或

 
  1. <?php  
  2. error_reporting(E_ALL); 
  3. class person { 
  4.      
  5.     public $name
  6.     public $age
  7.     public function __construct($name,$age){ 
  8.         $this->name = $name
  9.         $this->age = $age
  10.     }    
  11.  
  12.     public function __toString(){ 
  13.         return 'Object info name:'.$this->name.' age:'.$this->age; 
  14.     } 
  15.     public function __destruct(){ 
  16.          
  17.     }    
  18. $person = new person('Zhangsan','20'); 
  19. echo $person 

者print的时候会调用__toString()方法。

 

 



    本文转自kefirking 51CTO博客,原文链接:http://blog.51cto.com/phpzf/804722,如需转载请自行联系原作者




相关文章
|
1月前
|
Java 程序员 PHP
PHP对象和类
PHP对象和类
19 0
|
7月前
|
PHP
PHP 字符串
PHP 字符串
25 0
|
1月前
|
JSON JavaScript PHP
PHP把unicode编码的json字符串转中文
PHP把unicode编码的json字符串转中文
13 0
|
6月前
|
SQL 安全 PHP
理解php对象注入
php对象注入是一个非常常见的漏洞,这个类型的漏洞虽然有些难以利用,但仍旧非常危险,为了理解这个漏洞,请读者具备基础的php知识。
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧
php案例:自己写个数组转换成对象 对象转换成数组的的功能出来吧