PHP 中通过引用返回

发布于 2024-12-05 06:02:19 字数 216 浏览 0 评论 0原文

我尝试过谷歌搜索,尝试过 PHP 文档,在 Stack Overflow 上搜索答案,但找不到任何令人满意的东西。我正在读一本书,其中作者使用了按引用返回,但从未解释它是什么。作者使用的代码是

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

有人能用简单的话解释这个概念的例子吗?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

以往的大感动 2024-12-12 06:02:19

假设您有此类:

class Fruit {
    private $color = "red";

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

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

该类有一个私有属性和两个允许您访问它的方法。一种按值返回(默认行为),另一种按引用返回。两者之间的区别在于:

  • 当使用第一种方法时,您可以更改返回值,并且这些更改不会反映在 Fruit 的私有属性内,因为您实际上修改的是财产的价值。
  • 使用第二种方法时,您实际上会返回 Fruit::$color别名 - 您引用的不同名称同一个变量。因此,如果您对它执行任何操作(包括修改其内容),您实际上是直接对属性的值执行相同的操作。

下面是一些测试代码:

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"; 

查看实际操作

警告:我觉得有必要提及,虽然引用确实有合法用途,但它们是应该很少使用的功能之一,并且只有在您首先仔细考虑了任何替代方案的情况下才应使用。经验不足的程序员往往会过度使用引用,因为他们认为引用可以帮助他们解决特定问题,但同时却看不到使用引用的缺点(作为一项高级功能,其细微差别远非显而易见)。

Suppose you have this class:

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:

  • 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.

Here's some code to test it:

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).

戴着白色围巾的女孩 2024-12-12 06:02:19

简单规则:如果在 PHP 中将 & 放在函数名称前面,则可以在调用该函数时使用 &(即。它的返回值)就好像它是一个变量而不是一个函数。

就是这样。


更容易将其视为“PHP 允许您引用返回值”,而不是 PHP 通过引用返回。如上所述,您只需放置一个 & 来告诉 PHP 您想要这个,如果您不放置它并尝试执行 $var =& somefunction() 你会得到错误“只有变量应该通过引用分配。”

为了消除乔恩回答中的一些困惑。实际上没有必要有两个单独的函数,一个按引用返回,一个按值返回;在某些项目惯例之外。 &允许它通过引用返回,它不会强制它通过引用返回。

例如。相同的函数用于引用和非引用赋值

\header('content-type: text/plain');

class Demo
{
    protected $example = 'original value';

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

$demo = new Demo;

#1 - pass by value

$var1 = $demo->example();
$var1 = 'var1 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo PHP_EOL;

#2 - pass by reference

$var2 =& $demo->example();
$var2 = 'var2 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo '$var1 => '.$var1.PHP_EOL;
echo '$var2 => '.$var2.PHP_EOL;
echo PHP_EOL;

#3 - altering other references

$var3 =& $demo->example();
$var3 = 'var3 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo '$var1 => '.$var1.PHP_EOL;
echo '$var2 => '.$var2.PHP_EOL;
echo '$var3 => '.$var3.PHP_EOL;
echo PHP_EOL;

exit;

输出

$demo->example() => original value

$demo->example() => var2 value
$var1 => var1 value
$var2 => var2 value

$demo->example() => var3 value
$var1 => var1 value
$var2 => var3 value
$var3 => var3 value

引用很棒,但是如果您不熟悉它们,请遵循以下规则:

  • 仅在处理大型数组或类似数组时才考虑使用引用非对象数据结构
  • 从不引用对象(如果可以避免它)
  • 仅当值维护在对象的静态属性或属性中时才允许函数通过引用传递(即它不是函数内的临时变量

)显然是非常功利的用途(即。当您实际上想要共享一个值以简化操作它的代码时)。

再说一遍,永远不要引用对象(这是毫无意义的!)

Easy rule: if you place an & in front of a function name in PHP you can use & when you call the function (ie. it's return value) as if it was a variable and not a function.

That's it.


It's easier to think of it as "PHP allowing you to reference the return value" rather then PHP returning by reference. As mentioned above you simply place an & to tell PHP you want this, if you don't place it and try do to $var =& somefunction() you will get the error "Only variables should be assigned by reference."

To clear up some confusion with Jon's answer. There is actually no need to have two separate functions one returning by reference and one returning by value; outside of some project convention. The & only allows it to return by reference, it doesn't force it to return by reference.

eg. same function used both for reference and non-reference assignments

\header('content-type: text/plain');

class Demo
{
    protected $example = 'original value';

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

$demo = new Demo;

#1 - pass by value

$var1 = $demo->example();
$var1 = 'var1 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo PHP_EOL;

#2 - pass by reference

$var2 =& $demo->example();
$var2 = 'var2 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo '$var1 => '.$var1.PHP_EOL;
echo '$var2 => '.$var2.PHP_EOL;
echo PHP_EOL;

#3 - altering other references

$var3 =& $demo->example();
$var3 = 'var3 value';

echo '$demo->example() => '.$demo->example().PHP_EOL;
echo '$var1 => '.$var1.PHP_EOL;
echo '$var2 => '.$var2.PHP_EOL;
echo '$var3 => '.$var3.PHP_EOL;
echo PHP_EOL;

exit;

Output

$demo->example() => original value

$demo->example() => var2 value
$var1 => var1 value
$var2 => var2 value

$demo->example() => var3 value
$var1 => var1 value
$var2 => var3 value
$var3 => var3 value

References are great however if you're not familiar with them please follow the following rules:

  • only consider using references if you are dealing with large array or similar non-object data structures
  • never reference an object (if you can avoid it)
  • only allow a function to pass by reference if the value is maintained in a static property or attribute on the object (ie. it's not temporary variable inside the function)

Exceptions would obviously be very utilitarian uses (ie. when you actually want to share a value to simplify code for manipulating it).

Again, NEVER REFERENCE OBJECTS (it's pointless!)

染柒℉ 2024-12-12 06:02:19

您发布的示例可能来自 PHP4 或更早版本。不再需要通过引用返回对象,因为在 PHP5+ 中它们几乎总是自动以这种方式完成。

当您想要使用函数来执行以下操作时,通过引用返回非常有用
找到引用应该绑定到哪个变量。请勿使用
通过引用返回以提高性能。发动机将
自动对其进行优化。仅在以下情况下返回引用
您有充分的技术理由这样做。

请参阅返回 PHP 文档中的引用

The example you posted is probably from PHP4 or earlier. It's no longer necessary to return objects by reference as they are almost always done that way automatically in PHP5+.

Returning by reference is useful when you want to use a function to
find to which variable a reference should be bound. 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.

See return references in PHP docs

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文