4

PHP5 クラスで連鎖オブジェクトを作成するにはどうすればよいですか? 例:

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

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

4

3 に答える 3

7

実際、この質問はあいまいです。私にとって、この@Geoの答えは正しいものです。

あなた(@Anti)が言うことは作曲かもしれません

これは私の例です:

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

?>

于 2009-09-15T02:56:55.800 に答える
5

$myclass にインスタンス自体であるメンバー/プロパティがある限り、そのように機能します。

class foo {
   public $bar;
}

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

$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
于 2009-09-06T11:28:12.180 に答える
1

そのような関数呼び出しを連鎖させるには、通常、関数から self (または this ) を返します。

于 2009-09-06T11:30:16.800 に答える