当对象被 echo 语句中的变量引用时 运行 的魔术方法
Magic method to run when object is referenced by a variable in an echo statement
在 PHP 中,当引用对象的变量在 echo 语句中时,这种魔术方法会自动 运行 吗?
抱歉,我很难理解您的问题。我相信你想要 __toString()
方法:
The __toString()
method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj;
will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.
这是一个简单的例子:
class A
{
public function __toString()
{
return 'banana';
}
}
$a = new A();
echo $a;
这将打印出 banana
在 PHP 中,当引用对象的变量在 echo 语句中时,这种魔术方法会自动 运行 吗?
抱歉,我很难理解您的问题。我相信你想要 __toString()
方法:
The
__toString()
method allows a class to decide how it will react when it is treated like a string. For example, whatecho $obj;
will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.
这是一个简单的例子:
class A
{
public function __toString()
{
return 'banana';
}
}
$a = new A();
echo $a;
这将打印出 banana