为什么在 PHP 中通过引用传递?

Why Passing by Reference in PHP?

我写了一个函数,它应该接受一些变量然后改变这些变量的值。但是,在运行函数之后,变量保持不变。然后我做了一些谷歌搜索,发现你需要在变量名前面放一个 & 。然后代码做了我想要它做的事情。但是,我不明白您为什么需要放置 &。还有其他方法可以完成我需要做的事情吗?基本上我对通过引用传递的概念感到困惑。这就是我的麻烦开始的地方,大声笑:

在我目前学习的所有语言中(python、java、ruby),函数采用的参数会将变量的值更改为在没有任何 passing by reference 的情况下指导算法,这是我刚刚在 PHP 中发现的概念。为什么 PHP 选择这样做?你能解释一下引用背后的逻辑吗?最后,网络上有人在说:不要使用引用?如果没有,我还能如何找到我的解决方案。然后在 PHP 中的引用中也有弃用......抱歉,这是一个混乱。

我查阅了 PHP 手册作为参考,但我发现它很难消化。

这是我添加了 & 符号的一些代码:

<?php

$comments = "";
$airline_name = "United";
$flight_number = "262";
$departure_airport = "";

function airport(&$one, &$two, &$three, &$four) {
   if ( !empty($one) || !empty($two) || !empty($three) ) {
         $one = !empty($one) ? "Airline Name: $one<br>" :"Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
         $two = !empty($two) ? "Flight Number: $two<br>" : "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
         $three = !empty($three) ? "Departure Airport: $three<br>" : "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
         $four = !empty($four) ? "Comments: $four<br>" : "";
   }

}

airport($airline_name,$flight_number,$departure_airport,$comments);

echo $airline_name,$flight_number,$departure_airport,$comments;

?>

一些其他语言不需要这样做的原因是因为它们使用对象:改变对象的状态会反映到指向该对象的所有引用。但是,如果您在 Java 中传递原始类型(如 int)并且您更改了参数,则该值将不会更改。 Strings 同样的情况,因为你不能修改它们的状态,你只能修改作为参数传递的引用。请注意,它仍然是按值传递,因为您复制的引用基本上就是您的方法对对象的引用。

PHP 按值传递字符串,这意味着 - 至少在概念上 - 在调用它之前制作字符串的副本。

尽管如此,引用传递 有时被认为是危险的。它是 C 和 C++(甚至 C#)中使用的概念,但像 Java 这样的编程语言不允许这样做。您最好使用输出来启用变量修改,因为它在语法上是明确的:

function airport($one,$two,$three,$four) {
    if (!empty($one) || !empty($two) || !empty($three) ) {
        $one = !empty($one) ? "Airline Name: $one<br>" :"Airline Name: PLEASE PROVIDE AIRLINE NAME<br>";
        $two = !empty($two) ? "Flight Number: $two<br>" : "Flight Number: PLEASE PROVIDE FLIGHT NUMBER<br>";
        $three = !empty($three) ? "Departure Airport: $three<br>" : "Departure Airport: PLEASE PROVIDE DEPARTURE AIRPORT<br>";
        $four = !empty($four) ? "Comments: $four<br>" : "";
    }
    return array($one,$two,$three,$four);
}

并调用它:

list($airline_name,$flight_number,$departure_airport,$comments) = airport($airline_name,$flight_number,$departure_airport,$comments);

list is a special function where you call the variables by reference (yes, you do, it is actually a language construct as stated in the manual). The point is when you assign an array to a list construct, the elements in the array are assigned element-wise to the variables specified in the list. For example (taken from here):

list($drink, $color, $power) = array('coffee', 'brown', 'caffeine');

相当于:

$drink = 'coffee';
$color = 'brown';
$power = 'caffeine';

因此它或多或少与array相反:将数组拆分为元素并执行逐元素赋值。


使用list,大家很清楚这些变量会发生变化。此外,您不必查看函数签名即可知道变量是否会更改:它不会。如果您改变主意并想设置其他变量,那也很容易。