如何在PHP中回显自定义对象?

问题描述:

给出具有实例 foo 的特定类,有没有办法以自定义的方式安装PHP echo foo;?

Given a particular class with an instance foo, is there any way to have PHP echo foo; in a customized manner?

class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }
}

$foo = new TheClass();

echo $foo;

据我了解,您不能使echo重载,并且我意识到我可以轻松地使$foo->MrFunction()完成这项工作.但是我想知道是否有一种方法可以在其中进行编码

As I understand, you cannot overload echo and I realize I could easily have $foo->MrFunction() do the work. However I am wondering if there is a way to code in which

echo $foo打印出$foo->Name$foo->Number.

我们正在使用 PHP版本5.2.6 ,但升级不是问题.

We're using PHP Version 5.2.6 but upgrading is not an issue.

class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }

   public function __toString()
   {
     return $this->Name . ' '. $this->Number;
   }
}


echo $theClassInstance;