PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


later in the book, but you should think carefully before declaring something final. Are there really no
circumstances in which overriding would be useful? You could always change your mind later on, of
course, but this might not be so easy if you are distributing a library for others to use. Use final with
care.


Working with Interceptors


PHP provides built-in interceptor methods, which can intercept messages sent to undefined methods
and properties. This is also known as overloading, but since that term means something quite different
in Java and C++, I think it is better to talk in terms of interception.
PHP 5 supports three built-in interceptor methods. Like __construct(), these are invoked for you
when the right conditions are met. Table 4–2 describes the methods.


Table 4–2. The Interceptor Methods


Method Description

__get( $property ) Invoked when an undefined property is accessed

__set( $property, $value ) Invoked when a value is assigned to an undefined property

__isset( $property ) Invoked when isset() is called on an undefined property

__unset( $property ) Invoked when unset() is called on an undefined property

__call( $method, $arg_array ) Invoked when an undefined method is called

The get() and set() methods are designed for working with properties that have not been
declared in a class (or its parents).
get() is invoked when client code attempts to read an undeclared property. It is called
automatically with a single string argument containing the name of the property that the client is
attempting to access. Whatever you return from the
get() method will be sent back to the client as if
the target property exists with that value. Here’s a quick example:


class Person {
function __get( $property ) {
$method = "get{$property}";
if ( method_exists( $this, $method ) ) {
return $this->$method();
}
}


function getName() {
return "Bob";
}


function getAge() {
return 44;
}
}

Free download pdf