Are PHP Variables passed by value or by reference? Are PHP Variables passed by value or by reference? php php

Are PHP Variables passed by value or by reference?


It's by value according to the PHP Documentation.

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.

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


In PHP, by default, objects are passed as reference to a new object.

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.


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

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

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