PHP中 __toString()方法详解
作用:
__toString() 方法用于一个类被当成字符串时应怎样回应。例如 `echo $obj;` 应该显示些什么。
注意:
此方法必须返回一个字符串,否则将发出一条 `E_RECOVERABLE_ERROR` 级别的致命错误。
警告:
不能在 __toString() 方法中抛出异常。这么做会导致致命错误。
代码:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } public function __toString() { return 'go go go'; } } $person = new Person('小明'); // 初始赋值 echo $person;
结果:
go go go
那么如果类中没有 __toString() 这个魔术方法运行会发生什么呢?让我们来测试下:
代码:
<?php class Person { public $sex; public $name; public $age; public function __construct($name="", $age=25, $sex='男') { $this->name = $name; $this->age = $age; $this->sex = $sex; } } $person = new Person('小明'); // 初始赋值 echo $person;
结果:
Catchable fatal error: Object of class Person could not be converted to string in D:\phpStudy\WWW\test\index.php on line 18 很明显,页面报了一个致命错误,这是语法所不允许的。
以上就是PHP中 __toString()方法详解的详细内容,更多请关注教程集其它相关文章!
您可能感兴趣的文章:
php面向对象__toString() 用法详解
PHP中 __toString()方法详解
php 面向对象详解_常用的自动调用的方法
php以__开头的方法是什么
PHP之十六个魔术方法详解(总结)
PHP面向对象开发之魔术函数详解
如何使用PHP来实现枚举?
php define常量详解
PHP魔术常量、魔术函数、预定义常量详细介绍及实例讲解
php 魔术方法有哪些,作用是什么?