PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 4 ■ ADVANCED FEATURES

When a client attempts to access an undefined property, the get() method is invoked. I have
implemented
get() to take the property name and construct a new string, prepending the word “get”.
I pass this string to a function called method_exists(), which accepts an object and a method name and
tests for method existence. If the method does exist, I invoke it and pass its return value to the client. So
if the client requests a $name property:


$p = new Person();
print $p->name;


the getName() method is invoked behind the scenes.


Bob


If the method does not exist, I do nothing. The property that the user is attempting to access will
resolve to NULL.
The isset() method works in a similar way to get(). It is invoked after the client calls isset()
on an undefined property. Here’s how I might extend Person:


function __isset( $property ) {
$method = "get{$property}";
return ( method_exists( $this, $method ) );
}


Now a cautious user can test a property before working with it:

if ( isset( $p->name ) ) {
print $p->name;
}


The __set() method is invoked when client code attempts to assign to an undefined property. It is
passed two arguments: the name of the property, and the value the client is attempting to set. You can
then decide how to work with these arguments. Here I further amend the Person class:


class Person {
private $_name;
private $_age;


function __set( $property, $value ) {
$method = "set{$property}";
if ( method_exists( $this, $method ) ) {
return $this->$method( $value );
}
}


function setName( $name ) {
$this->_name = $name;
if (! is_null( $name ) ) {
$this->_name = strtoupper($this->_name);
}
}


function setAge( $age ) {
$this->_age = strtoupper($age);
}

Free download pdf