Search code examples
phpfluent-interfacemethod-chainingmagic-methodsphp-5.4

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


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 )

Solution

  • 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