0

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 )
Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

1

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

Dragony
  • 1,712
  • 11
  • 20
  • but it seems I can't access the properties inside the object, for instance, `$class = new TestClass($input); echo $class->title;` I get this error `Notice: Undefined property: TestClass::$title in C:...fluent_interface.php on line 23` instead of `page 1`... how can I access the data inside the object then? – Run Aug 22 '13 at 13:27
  • 1
    The foo property in your class contains another object that is your data. In your example you should use this syntax: $class->foo->title – Dragony Aug 22 '13 at 13:37
  • got it by doing that myself before reading your answer. thank you! :D – Run Aug 22 '13 at 13:37
1

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.

Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • thanks but how can I access the data inside the return object then? for instance, `echo $class->title;` I want to get `page 1` as the result. Is it possible? – Run Aug 22 '13 at 13:28
  • I'm not sure what are you trying to achieve. To replace your class instance by those, that was passed to constructor? If yes, why? – Alma Do Aug 22 '13 at 13:32
  • sorry, I got the answer by doing this `echo $class->foo->title;` thanks for the help. – Run Aug 22 '13 at 13:37