通过对Python的函数返回值返回的是值还是引用?的研究,引发了我对于php的函数返回值的思考:在php中,函数的返回值是变量的一份拷贝,那么php的函数返回值是否也可以返回变变量的引用呢?
答案是可以。只需要使用php的引用返回语法即可。
下面的代码演示了没有使用引用返回时的情况:
class Test
{
public $data = 'hi';
public function a()
{
return $this->data;
}
public function b()
{
$newData = $this->a();
echo $this->data . ' - ' . $newData . PHP_EOL; // hi - hi
$newData = 'hello';
echo $this->data . ' - ' . $newData . PHP_EOL; // hi - hello
}
}
$test = new Test();
$test->b();
因为a
函数的返回值不是引用,所以修改newData
变量的值对源值没有影响,两个变量指向的是不同的内容。
下面是来使用引用返回来看看效果:
class Test
{
public $data = 'hi';
public function &a()
{
return $this->data;
}
public function b()
{
$newData = &$this->a();
echo $this->data . ' - ' . $newData . PHP_EOL; // hi - hi
$newData = 'hello';
echo $this->data . ' - ' . $newData . PHP_EOL; // hello - hello
}
}
$test = new Test();
$test->b();
这里需要注意a
方法的定义和调用都加上了&
符号,分别表示引用返回和引用赋值,如果只是定义了引用返回但是赋值的时候不是引用赋值,那么拿到的也只是返回值的拷贝。
从上面的代码可以看出$newData
修改之后,原实例属性的值也同步变化了。
最后,虽然使用引用返回解决了文章开头提到的问题。但是在php的官方手册中也说到了,“不需要为了增加性能而刻意的使用引用返回,因为解释器会自动的帮我们优化好这一切”:
Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so.
所以对于phper来说,除非有特殊的使用场景,不然无需因为性能的原因来刻意的使用它。
完!
参考资料:
Returning References
网友评论