Page 222 - Beginning PHP 5.3
P. 222
Part II: Learning the Language
PHP allows you to create three “ magic ” methods that you can use to intercept property and
method accesses:
❑ __get() is called whenever the calling code attempts to read an invisible property of the object
❑ __set() is called whenever the calling code attempts to write to an invisible property of
the object
❑ __call() is called whenever the calling code attempts to call an invisible method of the object
What is meant by “ invisible ” ? In this context, invisible means that the property or method isn ’ t visible to
the calling code. Usually this means that the property or method simply doesn ’ t exist in the class, but it
can also mean that the property or method is either private or protected, and hence isn ’ t accessible to
code outside the class.
Overloading Property Accesses with __get() and __set()
To intercept attempts to read an invisible property, you create a method called __get() within your
class. (That ’ s two underscores, followed by the word get .) Your __get() method should expect a single
argument: the name of the requested property. It should then return a value; this value in turn gets
passed back to the calling code as the retrieved property value.
Here ’ s an example:
class Car {
public function __get( $propertyName ) {
echo “The value of ‘$propertyName’ was requested < br / > ”;
return “blue”;
}
}
$car = new Car;
$x = $car- > color; // Displays “The value of ‘color’ was requested”
echo “The car’s color is $x < br / > ”; // Displays “The car’s color is blue”
In this example, the Car class contains no actual properties, but it does contain a __get() method. This
method simply displays the value of the requested property name, and returns the value “blue”. The rest
of the script creates a new Car object, and attempts to retrieve the nonexistent property $car - > color ,
storing the result in a new variable, $x . Doing this triggers the Car object ’ s __get() method, which
displays the requested property name ( “ color “ ) and returns the literal string “blue” . This string is then
passed back to the calling code and stored in $x , as shown by the last line of code.
Similarly, to catch an attempt to set an invisible property to a value, use __set() . Your __set() method
needs two parameters: the property name and the value to set it to. It does not need to return a value:
public function __set( $propertyName, $propertyValue ) {
// (do whatever needs to be done to set the property value)
}
184
9/21/09 9:03:37 AM
c08.indd 184 9/21/09 9:03:37 AM
c08.indd 184