Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
327 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
", $this->what, $this->who);
    }

}

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

?>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...