我现在正在学习面向对象的php,我遇到了一个名为__toString()的魔术方法的问题。
没有要求该功能。它与其他神奇功能相似吗?
如果将它用于我的班级,那么它是否将所有对象都转换为字符串?
代码 -
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
// Create a new object
$obj = new MyClass;
// Output the object as a string
echo $obj;
// Destroy the object
unset($obj);
// Output a message at the end of the file
echo "End of file.<br />";
?>
输出 -
The class "MyClass" was initiated!
Using the toString method: I'm a class property!
The class "MyClass" was destroyed.
End of file.
答案 0 :(得分:4)
当该类的对象被用作字符串时,将调用magic __toString
方法:
class Something {
private $whatever;
public function __construct($whatever) {
$this->whatever = $whatever;
}
public function __toString() {
return $this->whatever;
}
}
$obj = new Something("Whatever here!");
echo "Object is $obj"; // Object is Whatever here!
请参阅 The Docs 。