PHP变量是按值传递还是按引用传递?


当前回答

似乎很多人都对对象传递给函数的方式和引用传递的含义感到困惑。对象仍然是按值传递的,只是PHP5中传递的值是引用句柄。证明:

<?php
class Holder {
    private $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function getValue() {
        return $this->value;
    }
}

function swap($x, $y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

输出:

a, b

通过引用传递意味着我们可以修改调用者看到的变量,显然上面的代码没有做到这一点。我们需要将swap函数更改为:

<?php
function swap(&$x, &$y) {
    $tmp = $x;
    $x = $y;
    $y = $tmp;
}

$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);

echo $a->getValue() . ", " . $b->getValue() . "\n";

输出:

b, a

为了通过引用传递。

其他回答

http://www.php.net/manual/en/migration5.oop.php

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

在PHP5中,包含基本类型的变量是按值传递的。包含对象的变量是通过引用传递的。2006年的Linux Journal上有一篇非常有趣的文章提到了4和5之间的OO差异。

http://www.linuxjournal.com/article/9170

实际上这两种方法都是有效的,但这取决于你的需求。通过引用传递值通常会使脚本变慢。因此,考虑到执行时间,最好按值传递变量。此外,当按值传递变量时,代码流更加一致。

可以通过引用将变量传递给函数。这个函数将能够修改原始变量。

你可以在函数定义中通过引用来定义段落:

<?php
function changeValue(&$var)
{
    $var++;
}

$result=5;
changeValue($result);

echo $result; // $result is 6 here
?>

PHP引用是一个别名,允许两个不同的变量写入相同的值。

在PHP中,如果你有一个包含对象的变量,这个变量不包含对象本身。相反,它包含该对象的标识符。对象访问器将使用标识符查找实际对象。因此,当我们在函数中使用对象作为参数或将其赋值给另一个变量时,我们将复制指向对象本身的标识符。

https://hsalem.com/posts/you-think-you-know-php.html

class Type {}

$x = new Type();
$y = $x;
$y = "New value";

var_dump($x); // Will print the object.
var_dump($y); // Will print the "New value"

$z = &$x; // $z is a reference of $x

$z = "New value";
var_dump($x); // Will print "New value"
var_dump($z); // Will print "New value"