php is pass by value

php primitive varialbles are passed by value to a function. Objects are also passed by value but the difference is that the value of the reference of the object is passed to a function. Prepending the ampersand to the paramter will make the parameter to be passed by references whether if the paramter is a primitve variable or an object variable.

php official object model definition.

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
class X {
  public $a = 10;
}
class Y {
	public $a = 20;
}

// the value of the reference of the object is passed into the function, 
// changes to the actual object the reference is pointing to will relect
// to all other references that are pointing to the same object.
function changeX1($v) {
	$v->a = 20;
}

// the value of the reference of the object is passed into the function,
// changes to the value of the reference stays inside the function.
function changeX2($v) {
	$v = new Y();
}

// The ampersand & makes the parameter to be passed by reference, the reference itself is passed to the function.
// Changes to the reference itself will change the same reference outside the function.
function changeX3(&$v) {
	$v = new Y();
}

// variable is passed by value, changes to variable only stays inside the function.
function changeX4($v) {
	$v = 20;
}

// array is passed by value, changes to variable only stays inside the function.
function changeX5($v) {
	$v['a'] = 20;
}

// By preppending the ampersand &, the varialbe is passed by reference, 
// thus changes to the variable inside the function will apply globally.
function changeX6(&$v) {
	$v = 20;
}

$x1=new X(); changeX1($x1); echo $x1->a . "\n"; // outputs 20
$x2=new X(); changeX2($x2); echo $x2->a . "\n"; // outputs 10
$x3=new X(); changeX3($x3); echo $x3->a . "\n"; // outputs 20

$x4=10; changeX4($x4); echo $x4 . "\n"; 				 // outputs 10
$x5=array('a'=>10); changeX5($x5); echo $x5['a'] . "\n"; // outputs 10
$x6=10; changeX6($x6); echo $x6 . "\n"; 				 // outputs 20

Search within Codexpedia

Custom Search

Search the entire web

Custom Search