Search code examples
phpclassoopchaining

Howto chain objects in PHP5: $this->foo->bar->baz()


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


Solution

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