Variables containing primitive types are passed by value in PHP5.
Variables containing objects are passed by references.
PHP Default Setting
- Object / Function
- call by reference
- Variables
- call by value
&
- force to make it call by reference
Introduce
- What is called by reference?
- Same Memory Location
- The value would be changed as the variable which has same reference
- What is called by value?
- Different Memory Location, even they have same value
- The value would not be changed when other variables changed
- But it would use a memory location
- it means it would cost some memory usaged
Example
- Call by Value would not change other variable
$a = "hello";
$b = $a;
// they have same value but different memory location
$b = "world";
echo $a; // "hello"
echo $b; // "world"
- The variables have same refernce would change their value together
class Car
{
public $name = "";
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
}
$a = new Car();
$a -> setName("toyota");
$b = $a; // $a $b have same reference
echo $b -> getName(); // "toyota"
echo $a -> getName(); // "toyota"
$b -> setName("honda");
echo $b -> getName(); // "honda"
echo $a -> getName(); // "honda"
- use
&
to force calling by reference
$A = "test";
$B = $A; // $A $B same value, different reference
echo $A; // "test"
echo $B; // "test"
$B = "new test";
echo $A; // "test"
echo $B; // "new test"
$C = &$B; // $C $B have same reference
echo $A; // "test"
echo $B; // "new test"
echo $C; // "new test"
$C = "final test";
echo $A; // "test"
echo $B; // "final test"
echo $C; // "final test"
// the value of $B would change
// due to have same reference with $C
- send variable with forcing by reference
$var1 = "foo";
$var2 = "bar";
// send the reference of $param2
function changeItem($param1, &$param2)
{
$param1 = "FOO";
$param2 = "BAR"; // change the value of the reference
}
changeItem($var1, $var2);
echo $var1; // "foo"
/** $param1 inside the function have
* different reference with $var1,
* therefore, it only
* calls by value here as the default
* setting of PHP
*/
echo $var2; // "BAR"
/**
* the value of the refernce was changed
* inside the function
*/
- send object to function
class Foo
{
public $var1;
function __construct()
{
$this->var1 = "foo";
}
public function printFoo()
{
print $this -> var1;
}
}
$foo = new Foo();
changeFoo($foo);
$foo -> printFoo(); // FOO
function changeFoo($foo)
{
$foo -> var1 = "FOO";
}