PHP programming - Classes and Objects
Frank Yap

In this section we'll see more of references, exceptions and namespaces.

Lab Exercises

Exercise 1: Use of references

foreach target $row modifies reference target $ref.

$ref = 0; 
$row =& $ref; 
foreach (array(1, 2, 3) as $row) { 
// do something 

echo $ref; // 3 - last element of the iterated array

Output ---
Modification of array element modifies reference target. Notice $b is also indicated as referenced.

$a = 1; 
$b = array(2, 3); 
$arr = array(&$a, &$b[0], &$b[1]); 
$arr[0]++; $arr[1]++; $arr[2]++; 
var_dump ($a); 
var_dump ($b); 
var_dump ($arr);

Output ---
int(2) array(2) { [0]=> &int(3) [1]=> &int(4) } array(3) { [0]=> &int(2) [1]=> &int(3) [2]=> &int(4) }
Assignment with value of reference target.

/* Assignment of scalar variables */ 
$a = 1; 
$b =& $a; 
$c = $b; // assigns the value of $a 
$c = 7; //$c is not a reference; no change to $a or $b 
var_dump ($a); 
var_dump ($b); 
var_dump ($c);

Output ---
int(1) int(1) int(7)
Array assignment is like assignment by reference.

/* Assignment of array variables */ 
$arr = array(1); 
$a =& $arr[0]; //$a and $arr[0] are in the same reference set 
$arr2 = $arr; //not an assignment-by-reference!, but behaves like reference 
var_dump ($a); 
var_dump ($arr);

Output ---
int(2) array(1) { [0]=> &int(2) }
Passing argument by reference.

function foo(&$var) 


var_dump ($a);

Output ---
Function returning a reference. Notice you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue.

class foo { 
public $value = 42; 
public function &getValue() { // & to indicate that reference is returned 
return $this->value; 

$obj = new foo; 
$myValue = &$obj->getValue(); // & to indicate that $myValue is a reference to $obj->value 
$obj->value = 2; 
echo $myValue; // prints the new value of $obj->value, i.e. 2.

Output ---
Exercise 2: Throwing an exception

Throwing an exception. Notice exception message is created by passing argument when exception is thrown.

class MyException extends Exception { } 
class Test { 
public function testing() { 
try { 
try { 
throw new MyException('foo!'); 
} catch (MyException $e) { 
/* rethrow it */ 
throw $e; 

} catch (Exception $e) { 

$foo = new Test; 

Output ---
string(4) "foo!"
Exercise 3: Use of namespaces

To exercise namespaces go here phpLab7_ns.php.
Homework Exercise

Continue to namespace section of Lab (phpLab7_ns.php) and complete homework in that section.