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

时间:2022-08-27 18:08:21

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

给定一个具有实例foo的特定类,有没有办法让PHP echo foo;以定制的方式?

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

据我所知,你不能重载回声,我意识到我可以很容易地让$ foo-> MrFunction()完​​成工作。但是我想知道是否有一种方法来编码

echo $foo prints out $foo->Name and $foo->Number.

echo $ foo打印出$ foo-> Name和$ foo-> Number。

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

我们使用的是PHP 5.2.6版,但升级不是问题。

4 个解决方案

#1


24  

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

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


echo $theClassInstance;

#2


9  

Yes, using the __toString magic method

是的,使用__toString魔术方法

#3


8  

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

你需要的是__toString()魔术方法。文档中的示例应该显示您需要的内容。

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

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

#4


8  

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

我想你正在寻找print_r($ foo)或var_dump($ foo)。

#1


24  

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

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


echo $theClassInstance;

#2


9  

Yes, using the __toString magic method

是的,使用__toString魔术方法

#3


8  

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

你需要的是__toString()魔术方法。文档中的示例应该显示您需要的内容。

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

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

#4


8  

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

我想你正在寻找print_r($ foo)或var_dump($ foo)。