如何在PHP OOP中从链接接口返回对象或数组?
我对用PHP OOP编写链接接口很感兴趣。我从php.net网站上修改了这个示例代码,我想更进一步——如何从这种接口返回对象或数组如何在PHP OOP中从链接接口返回对象或数组?,php,fluent-interface,method-chaining,magic-methods,php-5.4,Php,Fluent Interface,Method Chaining,Magic Methods,Php 5.4,我对用PHP OOP编写链接接口很感兴趣。我从php.net网站上修改了这个示例代码,我想更进一步——如何从这种接口返回对象或数组 // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() {
// Declare a simple class
class TestClass
{
public $foo;
public function __construct($foo)
{
$this->foo = $foo;
}
public function __toString()
{
return $this->foo;
}
}
$input = (object)array("title" => "page 1");
$class = new TestClass($input);
echo $class;
错误
可捕获的致命错误:方法TestClass::\uuuToString()必须返回
C:\wamp\www\test\2013\php\fluent\u interface.php在线中的字符串值
二,
那么,我应该使用不同的魔法方法而不是\uuuu toString
编辑:
我可以把这个作为结果返回吗
stdClass Object ( [title] => page 1 )
要获得所需内容,需要使用以下语法:
print_r($class->foo);
__toString()魔术方法试图将整个类“TestClass”转换为字符串,但由于魔术方法没有返回字符串,因此它向您显示了该错误。当然,您也可以重写_toString()方法来执行以下操作:
public function __toString()
{
return print_r($this->foo, true);
}
我认为您正在寻找或功能:
public function __toString()
{
return var_export($this->foo, true);
}
var_导出更好,因为它还返回值的类型(此外,以有效的PHP代码格式)。请注意,
\uu toString()
方法与fluent接口没有任何共同之处。这只是不同的事情。你到底想让它做什么?请参阅我上面的编辑。谢谢。但是我似乎无法访问对象内部的属性,例如,$class=newtestclass($input);echo$class->title代码>我得到了这个错误注意:未定义的属性:TestClass::$title在C:…fluent_interface.php的第23行
而不是第1页
。。。那么我如何访问对象内部的数据呢?类中的foo属性包含另一个对象,即您的数据。在您的示例中,您应该使用以下语法:$class->foo->titlegot,在阅读答案之前,您可以自己这样做。谢谢但我怎样才能访问返回对象中的数据呢?例如,echo$class->title代码>我想得到第1页
作为结果。有可能吗?我不知道你想达到什么目的。用传递给构造函数的类实例替换类实例?如果是,为什么?对不起,我是通过这样做得到答案的echo$class->foo->title代码>谢谢你的帮助。