gpt4 book ai didi

php - 如何在 PHP5 : $this->foo->bar->baz() 中链接对象

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:58:44 24 4
gpt4 key购买 nike

如何在 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) 说的可能是 composition

这是我的例子:

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

?>

关于php - 如何在 PHP5 : $this->foo->bar->baz() 中链接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1385429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com