如何在 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
如何在 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
实际上这个问题是模棱两可的......对我来说这个@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
?>
只要您的 $myclass 有一个成员/属性本身就是一个实例,它就会像那样工作。
class foo {
public $bar;
}
class bar {
public function hello() {
return "hello world";
}
}
$myclass = new foo();
$myclass->bar = new bar();
print $myclass->bar->hello();
为了像这样链接函数调用,通常你从函数中返回 self (或 this )。