我尝试使用谷歌搜索,尝试了PHP文档,搜索SO以获得答案,但找不到任何令人满意的结果.我正在读一本书,其中作者使用了Return by Reference,但从未解释过它是什么.作者使用的代码是
function &getSchool() {
return $this->school;
}
Run Code Online (Sandbox Code Playgroud)
有人可以用一个关于这个概念的例子用简单的词语来解释.
谢谢.
如果我有一个返回对不可见(私有或受保护)属性的引用的公共类方法,我可以使用该引用来获得直接访问:
PHP代码
class A
{
private $property = 'orange';
public function &ExposeProperty()
{
return $this->property;
}
public function Output()
{
echo $this->property;
}
}
$obj = new A();
# prints 'orange'
$obj->Output();
$var = &$obj->ExposeProperty();
$var = 'apple';
# prints 'apple'
$obj->Output();
Run Code Online (Sandbox Code Playgroud)
PHP 中的此功能背后是否有原因?还是只是设计上的疏忽,未能通过引用跟踪访问冲突?
当您想要实现以下目标时,它显然会派上用场:
PHP代码
$this->load->resource();
Run Code Online (Sandbox Code Playgroud)
哪里load是修改给定属性的对象$this。但是除了这个快捷方式,我没有看到很多可能的用途,否则有效的 OOP 模式是不可能的。