通过PHP返回引用 [英] Return by reference in PHP

查看:73
本文介绍了通过PHP返回引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了Googling,尝试了PHP文档,在Stack Overflow上搜索了答案,但找不到任何令人满意的方法.我正在读一本书,作者使用了参考归还",但从未解释过它是什么.作者使用的代码是

I tried Googling, tried PHP Documentation, searched Stack Overflow for an answer but couldn't find anything satisfactory. I was reading a book in which author have made use of Return by Reference but never explained what it is. The code used by the author is

function &getSchool() {
    return $this->school;
}

有人可以用一个简单的词来解释这个概念吗?

Can someone explain in simple words with an example about this concept.

推荐答案

假设您有此类:

class Fruit {
    private $color = "red";

    public function getColor() {
        return $this->color;
    }

    public function &getColorByRef() {
        return $this->color;
    }
} 

该类具有一个私有属性和两个使您可以访问它的方法.一个返回值(默认行为),另一个返回引用.两者之间的区别在于:

The class has a private property and two methods that let you access it. One returns by value (default behavior) and the other by reference. The difference between the two is that:

  • 使用第一种方法时,您可以更改返回的值,并且这些更改将不会反映在Fruit的私有属性中,因为您实际上是在修改该属性的值的副本.
  • 使用第二种方法时,实际上是在获取 Fruit::$color 的别名-一个不同的名称,您使用它来指代变量.因此,如果您对其进行任何操作(包括修改其内容),实际上就可以直接对属性值执行相同的操作.
  • When using the first method, you can make changes to the returned value and those changes will not be reflected inside the private property of Fruit because you are actually modifying a copy of the property's value.
  • When using the second method, you are in fact getting back an alias for Fruit::$color -- a different name by which you refer to the same variable. So if you do anything with it (including modifying its contents) you are in fact directly performing the same action on the value of the property.

下面是一些测试代码:

echo "\nTEST RUN 1:\n\n";
$fruit = new Fruit;
$color = $fruit->getColor();
echo "Fruit's color is $color\n"; 
$color = "green"; // does nothing, but bear with me
$color = $fruit->getColor();
echo "Fruit's color is $color\n"; 

echo "\nTEST RUN 2:\n\n";
$fruit = new Fruit;
$color = &$fruit->getColorByRef(); // also need to put & here
echo "Fruit's color is $color\n"; 
$color = "green"; // now this changes the actual property of $fruit
$color = $fruit->getColor();
echo "Fruit's color is $color\n"; 

查看实际效果 .

See it in action.

警告::我不得不提及参考文献虽然具有合理的用途,但它们是仅在您认真考虑了任何替代方法后才很少使用的那些功能之一.首先.经验不足的程序员倾向于过度使用引用,因为他们看到他们可以帮助他们解决特定的问题,而又没有看到使用引用的缺点(作为高级功能,它的细微差别很明显).

Warning: I feel obliged to mention that references, while they do have legitimate uses, are one of those features that should be used only rarely and only if you have carefully considered any alternatives first. Less experienced programmers tend to overuse references because they see that they can help them solve a particular problem without at the same time seeing the disadvantages of using references (as an advanced feature, its nuances are far from obvious).

这篇关于通过PHP返回引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆