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

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

php - 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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

?>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...