Objects and references
There are two ways to pass arguments within the code:
- By reference: This is where both the caller and callee use the same variable for argument.
- By value: This is where both the caller and callee have their own copy of the variable for argument. If the callee decides to change the value of the passed argument, the caller would not notice it.
by value is the default PHP behavior, as shown in the following example:
<?php class Util { function hello($msg) { $msg = "<p>Welcome $msg</p>"; return $msg; } } $str = 'John'; $obj = new Util(); echo $obj->hello($str); // Welcome John echo $str; // John
Looking at the internals of the hello()
method, we can see it is resetting the $msg
argument value to another string value wrapped in HTML tags. The default PHP passed by the value behavior prevents this change to propagate outside the scope of a method. Using the &
operator just before the argument name in the function definition, we can force...