tags:

views:

444

answers:

3

How do I make chained objects in PHP5 classes? Examples:

$myclass->foo->bar->baz();
$this->foo->bar->baz();
Not: $myclass->foo()->bar()->baz();

See also:
http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html

Thanks.

/Kristoffer :-)

+1  A: 

As long as your $myclass has a member/property that is an instance itself it will work just like that.

class foo {
   public $bar;
}

class bar {
    public function hello() {
       return "hello world";
    }
}

$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
Anti Veeranna
Anti Veeranna's solution fits my purpose - to make readable, self-documenting code (when methods are called across classes).
Kristoffer Bohmann
+1  A: 

In order to chain function calls like that, usually you return self ( or this ) from the function.

Geo
The question is confusing, but I think this is exactly what he does NOT want to do :)
Anti Veeranna
Exactly. The purpose is to "self-document" calls to methods in other classes. Good: $url->anchor(). Bad: $this->anchor(). :-)
Kristoffer Bohmann
A: 

actually this questions is ambiguous.... for me this @Geo's answer is right one.

What you (@Anti) says could be composition

This is my example for this:

<?php
class Greeting {
    private $what;
    private $who;


    public function say($what) {
     $this->what = $what;
     return $this;
    }

    public function to($who) {
     $this->who = $who;
     return $this;
    }

    public function __toString() {
     return sprintf("%s %s\n", $this->what, $this->who);
    }

}

$greeting = new Greeting();
echo $greeting->say('hola')->to('gabriel'); // will print: hola gabriel

?>

Gabriel Sosa
Might I also add that this is a very elegant way of coding.
Tres
Very interesting coding. One caveat seems to be that it doesn't "document" method calls across classes - as in $url->anchor(). Still, I'm sure I will find a use for this coding style some day. Thanks.. :-)
Kristoffer Bohmann