[英]Unable to understand __toString() function OOP PHP
我现在正在学习面向对象的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.
当该类的对象用作字符串时,将调用魔术__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!
请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.