Page 223 - Beginning PHP 5.3
P. 223
Chapter 8: Objects
Try It Out Using __get() and __set()
The following example shows how __get() and __set() can be used to store “ nonexistent ”
properties in a private array. This effectively creates a class with a potentially unlimited number of
“ virtual ” properties that are kept safely away from any real properties of the class. This technique can
be useful for creating classes that need to hold arbitrary data.
Save the following script as get_set.php in your document root folder and run it in your browser.
You should see the result shown in Figure 8 - 3 .
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Using __get() and __set() < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Using __get() and __set() < /h1 >
< ?php
class Car {
public $manufacturer;
public $model;
public $color;
private $_extraData = array();
public function __get( $propertyName ) {
if ( array_key_exists( $propertyName, $this- > _extraData ) ) {
return $this- > _extraData[$propertyName];
} else {
return null;
}
}
public function __set( $propertyName, $propertyValue ) {
$this- > _extraData[$propertyName] = $propertyValue;
}
}
$myCar = new Car();
$myCar- > manufacturer = “Volkswagen”;
$myCar- > model = “Beetle”;
$myCar- > color = “red”;
$myCar- > engineSize = 1.8;
$myCar- > otherColors = array( “green”, “blue”, “purple” );
185
9/21/09 9:03:37 AM
c08.indd 185
c08.indd 185 9/21/09 9:03:37 AM