How to echo a custom object in PHP?

2019-02-06 04:57发布

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;

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 prints out $foo->Name and $foo->Number.

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

4条回答
Fickle 薄情
2楼-- · 2019-02-06 05:06

What you need is the __toString() magic method. The example in the docs should show what you need.

http://www.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring:

查看更多
我只想做你的唯一
3楼-- · 2019-02-06 05:08
class TheClass {
    public $Name;
    public $Number;
    function MrFunction() { /* bla bla bla */ }

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


echo $theClassInstance;
查看更多
Anthone
4楼-- · 2019-02-06 05:10

I think you are looking for print_r($foo), or var_dump($foo).

查看更多
家丑人穷心不美
5楼-- · 2019-02-06 05:16

Yes, using the __toString magic method

查看更多
登录 后发表回答