1. References as a function’s parameter
By default, PHP handle the variables you send to a function locally, what I mean is what is in the function stay in the function. By passing a reference you will make your local function variable referencing to the variable in the calling scope of your application. Here is a short example with and without references.
<?php
/**
* Using references
*/
function foo(&$var){
$var++;
}
$a=5;
foo($a);
echo($a); //Will display 6
?>
<?php
/**
* Without references
*/
function foo($var){
return $var++;
}
$a=5;
$a=foo($a);
echo($a); //will display 6
?>
2. Return by references
Another case is to return a reference. But you have to be very careful with this one because with some tricky code you can access to the private attributes of a class and indeed modify their values.
Here is a classic use of a return reference:
<?php
class Personne {
public $age = 22;
public function &getAge() {
return $this->age;
}
}
$obj = new Personne();
$myAge = &$obj->getAge(); //$myAge is a reference to $obj->age, which is 22.
$obj->age = 18;
echo $myAge; //will display 18
?>
And now we will see that we can modify a private attribute by using a return reference:
<?php
class Personne {
private $age = 22;
public function &getAge() {
return $this->age;
}
public function __toString(){
return $this->age;
}
}
$obj = new Personne();
$myAge = &$obj->getAge();
$myAge = 897; //the private attribute $age has been modified
echo($obj); //unfortunately it will display 897
?>
3. Assign by references
The last case and the easiest is the assignment. It is done just like that:
<?php
$a =& $b;
?>
Which means that $a and $b reference to the same content.
In conclusion, references might seems pretty useless with these examples but it is actually wise to use some of them when you are working on a complex software architecture with a lot of objects using others objects. It is also nicer to avoid the $var=foo($var).
No comments:
Post a Comment