Kri*_*ann 4 php oop class chaining
如何在PHP5类中创建链接对象?例子:
$myclass->foo->bar->baz();
$this->foo->bar->baz();
Not: $myclass->foo()->bar()->baz();
Run Code Online (Sandbox Code Playgroud)
另见:http:
//www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html
实际上这个问题含糊不清......对我而言,@ 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
Run Code Online (Sandbox Code Playgroud)
?>
只要你的$ myclass有一个成员本身就是一个实例,它就会像那样工作.
class foo {
public $bar;
}
class bar {
public function hello() {
return "hello world";
}
}
$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
Run Code Online (Sandbox Code Playgroud)