PHP变量是通过值传递还是通过引用传递?

时间:2022-06-09 16:08:47

Are PHP variables passed by value or by reference?

PHP变量是通过值传递还是通过引用传递?

13 个解决方案

#1


216  

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.

要使一个函数的参数始终通过引用传递,在函数定义中prepend an & &(&)到参数名。

<?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.'
?>

#2


52  

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 reference means 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:

通过引用传递,我们可以修改调用者所看到的变量。上面的代码显然没有这么做。我们需要将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";

Outputs:

输出:

b, a

in order to pass by reference.

为了通过引用。

#3


38  

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.

我希望你能理解。

#4


24  

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版本中,对象的处理方式类似于基本类型(例如整数和字符串)。这种方法的缺点是,在分配变量或作为参数传递给方法时,从语义上复制整个对象。在新方法中,对象是通过句柄引用的,而不是通过值引用的(可以将句柄视为对象的标识符)。

#5


19  

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: test, var2: final test, var3: final test

Passed by value/reference exampe:

通过价值/参考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...)

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

#6


7  

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

#7


5  

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.

#8


4  

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杂志上有一篇相当有趣的文章提到了4和5之间的OO差异。

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

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

#9


1  

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

#10


1  

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

#11


0  

Actually both the methods are valid but it depends upon your requirement.Pass values by reference often makes your script slow. So its better to pass variables by value by considering time of execution. Also the code flow is more consistent when you pass variables by value.

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

#12


0  

Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.

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

function add(&$var){ // The &amp; 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

#13


-6  

Depends on the version, 4 is by value, 5 is by reference.

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

#1


216  

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.

要使一个函数的参数始终通过引用传递,在函数定义中prepend an & &(&)到参数名。

<?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.'
?>

#2


52  

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 reference means 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:

通过引用传递,我们可以修改调用者所看到的变量。上面的代码显然没有这么做。我们需要将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";

Outputs:

输出:

b, a

in order to pass by reference.

为了通过引用。

#3


38  

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.

我希望你能理解。

#4


24  

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版本中,对象的处理方式类似于基本类型(例如整数和字符串)。这种方法的缺点是,在分配变量或作为参数传递给方法时,从语义上复制整个对象。在新方法中,对象是通过句柄引用的,而不是通过值引用的(可以将句柄视为对象的标识符)。

#5


19  

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: test, var2: final test, var3: final test

Passed by value/reference exampe:

通过价值/参考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...)

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

#6


7  

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

#7


5  

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.

#8


4  

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杂志上有一篇相当有趣的文章提到了4和5之间的OO差异。

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

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

#9


1  

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

#10


1  

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

#11


0  

Actually both the methods are valid but it depends upon your requirement.Pass values by reference often makes your script slow. So its better to pass variables by value by considering time of execution. Also the code flow is more consistent when you pass variables by value.

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

#12


0  

Use this for functions when you wish to simply alter the original variable and return it again to the same variable name with its new value assigned.

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

function add(&$var){ // The &amp; 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

#13


-6  

Depends on the version, 4 is by value, 5 is by reference.

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