Pergunta

I am curious in writing a chaining interface in PHP OOP. I modified this sample code from the php.net website, and I want to take it further - how can I return objects or arrays from this kind of interface?

// 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;

error,

Catchable fatal error: Method TestClass::__toString() must return a string value in C:\wamp\www\test\2013\php\fluent_interface.php on line 2

Should I use different magic method instead of __toString then?

EDIT: Can I return this as my result,

stdClass Object ( [title] => page 1 )
Foi útil?

Solução

To get what you want you need to use following syntax:

print_r($class->foo);

The __toString() magic method tries to convert your whole class 'TestClass' to a string, but since the magic method is not returning a string, it is showing you that error. Of course you could also rewrite your __toString() method to do the following:

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

Outras dicas

I think you are looking for either print_r or var_export functions:

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

and var_export is better since it also return type of value (and, besides, in valid PHP-code format). Note, that __toString() method have nothing common with fluent interface. It's just different things.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top