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


当前回答

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

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

其他回答

在PHP 5中通过引用传递对象,在PHP 4中通过值传递对象。 默认情况下,变量是按值传递的!

阅读此处:http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html

当您希望简单地更改原始变量并将其返回到相同的变量名并赋予其新值时,可以将此用于函数。

function add(&$var){ // The & is before the argument $var
   $var++;
}
$a = 1;
$b = 10;
add($a);
echo "a is $a,";
add($b);
echo " a is $a, and b is $b"; // Note: $a and $b are NOT referenced

取决于版本,4是值,5是引用。

两种方法都可以。

在前面放一个“&”符号,你传递的变量就变成了它的原点,也就是说,你可以通过引用传递,而不是复制它。

so

    $fred = 5;
    $larry = & $fred;
    $larry = 8;
    echo $fred;//this will output 8, as larry and fred are now the same reference.

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