如何在 PHP 中回显自定义对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6012019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to echo a custom object in PHP?
提问by Garet Claborn
Given a particular class with an instance foo, is there any way to have PHP echo foo;
in a customized manner?
给定一个具有实例foo的特定类,有没有办法以echo foo;
自定义方式拥有 PHP ?
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->MrFunction()
完成这项工作。但是我想知道是否有一种方法可以在其中进行编码
echo $foo
prints out $foo->Name
and $foo->Number
.
echo $foo
打印出来$foo->Name
和$foo->Number
。
We're using PHP Version 5.2.6but upgrading is not an issue.
我们使用的是PHP 5.2.6 版,但升级不是问题。
回答by prodigitalson
class TheClass {
public $Name;
public $Number;
function MrFunction() { /* bla bla bla */ }
public function __toString()
{
return $this->Name . ' '. $this->Number;
}
}
echo $theClassInstance;
回答by Steve Mallory
I think you are looking for print_r($foo)
, or var_dump($foo)
.
我认为您正在寻找print_r($foo)
, 或var_dump($foo)
。
回答by onteria_
Yes, using the __toStringmagic method
是的,使用__toString魔术方法
回答by CVM
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: