Argument pass by value
This is the easiest and most common method. This we discussed earlier.One more example is
<?php
$name = "google";
function SearchEngine($name) {
return "$name is a Search engine.";
}
print SearchEngine($name);
?> |
when you pass a variable like this even if you use the same name,
changes to the variable within the function will not affect the
variable outside the function. Lok the following example
<?php
$Z = 50;
function add($Z) {
$y++;
print $y;
}
add($Z);
print $Z;
?> |
Argument pass by reference
This method is very similar to the first; however instead of copying the value of a variable to a new one within a function, you are pointing the new variable name to the same value.
Consider the following example, there the "&" before the variable name in the function definition, which marks it as a reference
<?php
$Z = 1;
function sum(&$y) {
$y++;
}
sum($Z);
print $Z;
?> |
Since we are altering the actual value of $Z from within the function, there is no need to even return anything from the function. When $Z is printed out, its value will have increased by one.
Declare the variable global within the function
By declaring a variable as global within the function, all references to either variable will refer to the global version. There is no limit to the number of global variables in a function.
<?php
$Z = 1;
function sum() {
global $Z;
$Z++;
}
sum();
print $Z;
?> |
All global variables will contain in $GLOBALS array.The $GLOBALS array is an associative array with the name of the global variable being the key and the contents of that variable being the value of the array element.
Difference between Call by value and Call by reference
Pass by value means that when you pass the variable by sending it as an argument to a function,
or assigning it to another variable using an assignment operator, a copy of the value of the variable
is made and that is what is passed to the receiving function or variable.
It works like this: If I set $a equal to 10, and then say $b = $a,
I will then have two variables each storing the value if 10.
If I change either one, it won't affect the other one. It is like a photocopy.
After I have made the copies, writing something on one copy won't affect the other copies.
Pass by reference is a little more complicated and normally only occurs in object
oriented environments. To understand it, it first helps to understand that variables are
actually just pointers pointing to values stored in memory. Pass by value works by creating
a new pointer pointing to a new location in memory with a copy of the stuff from the old
location copied over to the new location. Pass by reference created a new pointer but points
it to the exact same location. It is not actually passing the value anywhere,
it is just creating new variables pointing to the exact same thing. Another way of saying
it is that it creates an alias for the current variable instead of making a copy.