尝试学习OO PHP,但我对某些东西感到困惑。我以前使用过框架,它们将->链接在一起以调用这些函数中的多个函数或变量。
ex. $variable = $this->query($stmt)->result()->name;
你会如何设置这个?
class test{
public $name;
public function __construct(){
$this->name = 'Jon'; // pretending that Jon is a db call result
}
public function change_name($n){
$this->name = $n;
}
public function get_name(){
return $this->name;
}
}
$i = new test();
我该怎么做呢?还是说这完全不可能。
$i->change_name('george')->get_name; // as an example
当你说"链接"时,你真正的意思是"链接"
在您的示例中我-> change_name(乔治)-> get_name;//作为例子
(!)你有两个错误
1) ->get_name应该是->get_name();//它是一个函数而不是一个属性
2)即使使用->get_name(),也不能工作,因为它没有上下文。
示例:
当你这样做的时候:$i->change_name('george')//方法change_name()有上下文$i
我们继续:
$i->change_name('george')->get_name() // the method get_name() have the context returned by change name, in your case its nothing because your function change_name return nothing
如果我们看你的change_name body:
public function change_name($n){
$this->name = $n;
}
不返回任何值,这意味着该函数返回空值或者不返回任何值。
在你的例子中,你想要的是返回对象上下文,"$this"
试题:
public function change_name($n){
$this->name = $n;
return $this;
}
做你想做的事:
$i->change_name('george')->get_name()//方法change_name()有通过更改名称返回的上下文,现在它的工作
从change_name()
返回$this
public function change_name($n){
$this->name = $n;
return $this;
}
这叫做方法链。你可以实现它:
我建议你参考这个链接:
方法链接?