4

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

2
  • remember you are able change your accepted answer :P Commented Sep 15, 2009 at 2:58
  • 1
    Gabriel Sosa is right. Chaining should be done through the methods return value (i.e. return $this;) and using $this->method1()->method2() rather than assigning an object to properties and using $this->obj1->obj2, which is unnecessary in most cases and can cause confusion. Commented Sep 15, 2009 at 3:10

3 Answers 3

7

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

?>

Sign up to request clarification or add additional context in comments.

2 Comments

Might I also add that this is a very elegant way of coding.
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.. :-)
5

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();

1 Comment

Anti Veeranna's solution fits my purpose - to make readable, self-documenting code (when methods are called across classes).
1

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

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.