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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:07:22  来源:igfitidea点击:

Are PHP Variables passed by value or by reference?

phpvariablespass-by-referencepass-by-value

提问by cmcculloh

Are PHP variables passed by value or by reference?

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

回答by Michael Stum

It's by value according to the PHP Documentation.

根据PHP 文档,它是按价值计算的。

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

默认情况下,函数参数是按值传递的(因此,如果函数内参数的值发生更改,则不会在函数外更改)。要允许函数修改其参数,它们必须通过引用传递。

要始终通过引用传递函数的参数,请在函数定义中的参数名称前添加一个与号( &)。

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

回答by hardik

In PHP, By default objects are passed as reference copy to a new Object.

在 PHP 中,默认对象作为引用副本传递给新对象。

See this example.............

看这个例子………………

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue($obj)
  {
   $obj->abc = 30;
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 30

Now see this..............

现在看这个…………

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue($obj)
  {
    $obj = new Y();
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 10 not 20 same as java does.

Now see this ..............

现在看这个………………

class X {
  var $abc = 10; 
}

class Y {

  var $abc = 20; 
  function changeValue(&$obj)
  {
    $obj = new Y();
  }
}

$x = new X();
$y = new Y();

echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 20 not possible in java.

i hope you can understand this.

我希望你能理解这一点。

回答by grom

It seems a lot of people get confused by the way objects are passed to functions and what pass by reference means. Object variables are still passed by value, its just the value that is passed in PHP5 is a reference handle. As proof:

似乎很多人对对象传递给函数的方式以及通过引用传递的方式感到困惑。对象变量仍然是按值传递的,它只是在 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";

Outputs:

输出:

a, b

To pass by referencemeans we can modify the variables that are seen by the caller. Which clearly the code above does not do. We need to change the swap function to:

为了按引用传递手段,我们可以修改被调用者得到的变量。上面的代码显然没有做到这一点。我们需要将交换函数更改为:

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

Outputs:

输出:

b, a

in order to pass by reference.

以便通过引用传递。

回答by Karl Seguin

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

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

在 PHP 5 中有一个新的对象模型。PHP 对对象的处理已完全重写,从而提供更好的性能和更多功能。在以前的 PHP 版本中,对象像原始类型一样处理(例如整数和字符串)。这种方法的缺点是,在分配变量或作为参数传递给方法时,整个对象在语义上被复制。在新方法中,对象通过句柄而不是值来引用(可以将句柄视为对象的标识符)。

回答by cmcculloh

PHP variables are assigned by value, passed to functions by value, and when containing/representing objects are passed by reference. You can force variables to pass by reference using an &

PHP 变量按值分配,按值传递给函数,当包含/表示对象时按引用传递。您可以使用 & 强制变量通过引用传递

Assigned by value/reference example:

按值分配/参考示例:

$var1 = "test";
$var2 = $var1;
$var2 = "new test";
$var3 = &$var2;
$var3 = "final test";

print ("var1: $var1, var2: $var2, var3: $var3);

would output

会输出

var1: test, var2: final test, var3: final test

var1:测试,var2:最终测试,var3:最终测试

Passed by value/reference exampe:

通过值/参考示例:

$var1 = "foo";
$var2 = "bar";

changeThem($var1, $var2);

print "var1: $var1, var2: $var2";

function changeThem($var1, &$var2){
    $var1 = "FOO";
    $var2 = "BAR";
}

would output:

会输出:

var1: foo, var2 BAR

var1: foo, var2 酒吧

Object variables passed by reference exampe:

通过引用实例传递的对象变量:

class Foo{
    public $var1;

    function __construct(){
        $this->var1 = "foo";
    }

    public function printFoo(){
        print $this->var1;
    }
}


$foo = new Foo();

changeFoo($foo);

$foo->printFoo();

function changeFoo($foo){
    $foo->var1 = "FOO";
}

Would output:

会输出:

FOO

食品级

(that last example could be better probably...)

(最后一个例子可能会更好......)

回答by Mahsin

You can pass a variable to a function by reference. This function will be able to modify the original variable.

您可以通过引用将变量传递给函数。这个函数就能修改原来的变量。

You can define the passage by reference in the function definition:

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

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

$result=5;
changeValue($result);

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

回答by Bingy

You can do it either way.

你可以用任何一种方式来做。

put a '&' symbol in front and the variable you are passing becomes one and the same as its origin. ie: you can pass by reference, rather than making a copy of it.

在前面放一个 '&' 符号,你传递的变量就变成了一个和它的原点相同的变量。即:您可以通过引用传递,而不是复制它。

so

所以

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

回答by Polsonby

Variables containing primitive types are passed by value in PHP5. Variables containing objects are passed by reference. There's quite an interesting article from Linux Journal from 2006 which mentions this and other OO differences between 4 and 5.

包含原始类型的变量在 PHP5 中是按值传递的。包含对象的变量通过引用传递。2006 年 Linux Journal 上有一篇非常有趣的文章,其中提到了这一点以及 4 和 5 之间的其他面向对象差异。

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

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

回答by Miha

Objects are passed by reference in PHP 5 and by value in PHP 4. Variables are passed by value by default!

对象在 PHP 5 中通过引用传递,在 PHP 4 中通过值传递。变量默认通过值传递!

Read here: http://www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html

在这里阅读:http: //www.webeks.net/programming/php/ampersand-operator-used-for-assigning-reference.html

回答by Ricardo Saracino

class Holder
{
    private $value;

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

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

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

class Swap
{       
    public function SwapObjects( Holder $x, Holder $y )
    {
        $tmp = $x;

        $x = $y;

        $y = $tmp;
    }

    public function SwapValues( Holder $x, Holder $y )
    {
        $tmp = $x->getValue();

        $x->setValue($y->getValue());

        $y->setValue($tmp);
    }
}


$a1 = new Holder('a');

$b1 = new Holder('b');



$a2 = new Holder('a');

$b2 = new Holder('b');


Swap::SwapValues($a1, $b1);

Swap::SwapObjects($a2, $b2);



echo 'SwapValues: ' . $a2->getValue() . ", " . $b2->getValue() . "<br>";

echo 'SwapObjects: ' . $a1->getValue() . ", " . $b1->getValue() . "<br>";

Attributes are still modifiable when not passed by reference so beware.

当不通过引用传递时,属性仍然可以修改,所以要小心。

Output:

输出:

SwapObjects: b, a SwapValues: a, b

SwapObjects: b, a SwapValues: a, b