如何在PHP OOP中从链接接口返回对象或数组


How to return objects or arrays from a chaining interface in PHP OOP?

我很想用PHP OOP编写一个链接接口。我从php.net网站上修改了这个示例代码,我想更进一步——如何从这种接口返回对象或数组?

// 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::__toString()必须返回C:''wamp''www''test''2013''php''fluent_interface.php中的字符串值2

那么我应该用不同的魔术方法代替__toString吗?

编辑:,我可以将此作为我的结果返回吗

stdClass Object ( [title] => page 1 )

要获得所需内容,需要使用以下语法:

print_r($class->foo);

__toString()magic方法试图将整个类"TestClass"转换为字符串,但由于magic方法没有返回字符串,因此它会向您显示错误。当然,您也可以重写__toString()方法来执行以下操作:

public function __toString()
{
    return print_r($this->foo, true);
}

http://php.net/manual/en/function.print-r.php

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

我认为您正在寻找print_r或var_export函数:

public function __toString()
{
    return var_export($this->foo, true);
}

var_export更好,因为它还返回值的类型(此外,还返回有效的PHP代码格式)。注意,__toString()方法与fluent接口没有任何共同之处。这只是不同的事情。