如何使用 php __toString [英] How to use php __toString
本文介绍了如何使用 php __toString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
__toString
在 PHP 中有什么用途?
What are the uses of __toString
in PHP?
例如,我有一个函数,例如(在名为 person 的类中)
For example I have a function such as (inside a class called person)
public function __construct($id, $name) {
$this->id = $id;
$this->name= $name;
}
和
$person= new person("12","James");
$person->setDescription("Test Description");
$person->setImage("Test Image");
如何使用 __toString
获取这些数据并将它们打印在一行上.
How can I use __toString
to grab this data and print them on one line.
例如: 12 测试描述 James 测试图像
推荐答案
__toString()
方法用于如果您尝试回显对象实例而不是该对象的简单属性.通常会抛出异常,但是 to_string 方法定义了一个响应
The __toString()
method is used if you try to echo an object instance rather than simply properties of that object. Normally that would throw an exception, but the to_string method defines a response
class person{
public function __construct($id, $name) {
$this->id = $id;
$this->name= $name;
}
public function __toString() {
return $this->id . ' ' . $this->name;
}
}
$person= new person("12","James");
echo $person;
__toString()
返回将被回显的值
这篇关于如何使用 php __toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文