Mostly correct.
Like in most languages, arguments given to a PHP function are normally
by value, which means the
value of the variable is used. There is no direct access to the variable itself.
Inside foo(), $var will be a
copy of whatever $bar is*. It then modifies the copy on line 4. $bar will not have the new value because it itself was not modified.
You can change this behavior with an &.
This means $bar will be passed
by reference, meaning a
reference is used. On line 4 $var is updated, and since it is a reference to the $bar variable, $bar will be updated too.
Code: Select all
function foo_byvalue($var) {
$var = "by value";
return $var;
}
echo foo_byvalue($bar1); // "Notice: Undefined variable: bar1" "by value"
echo $bar1; // "Notice: Undefined variable: bar1"
$bar1 = "bar";
foo_byvalue($bar1); echo $bar1; // "bar"
function foo_byref(&$var) {
$var = "by reference";
return $var;
}
echo foo_byref($bar2); // "by reference"
echo $bar2; // "by reference"
$bar2 = "bar";
foo_byref($bar2); echo $bar2; // "by reference"
You have to give a variable when passing by-reference:
Code: Select all
echo foo_byref("a literal string"); // "Fatal error: Only variables can be passed by reference"
// for php 5 the rules are still enforced but you get a little leeway
echo foo_byref($bar3 = "a literal string"); // "Strict Standards: Only variables should be passed by reference" "by reference"
echo $bar3; // "a literal string"
// PHP is complaining since ($bar3 = "a literal string") is technically an expression, not a variable
// however it realizes that it can do the expression and use $bar3 as a variable, thus making everybody happy
// so while this is bad practice, PHP lets you get away with it
* You are (mostly) correct: $bar doesn't have a value because it doesn't exist. But since you forced it to by trying to use it, PHP set a "default value" of null. Thus $var will exist and
is_null($var) == true. PHP also issues a warning message when it does this but you might not see it depending on your php.ini settings.