PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 9 ■ GENERATING OBJECTS

return self::$instance;
}


public function setProperty( $key, $val ) {
$this->props[$key] = $val;
}


public function getProperty( $key ) {
return $this->props[$key];
}
}


The $instance property is private and static, so it cannot be accessed from outside the class. The
getInstance() method has access though. Because getInstance() is public and static, it can be called via
the class from anywhere in a script.


$pref = Preferences::getInstance();
$pref->setProperty( "name", "matt" );


unset( $pref ); // remove the reference


$pref2 = Preferences::getInstance();
print $pref2->getProperty( "name" ) ."\n"; // demonstrate value is not lost


The output is the single value we added to the Preferences object initially, available through a
separate access:


matt


A static method cannot access object properties because it is, by definition, invoked in a class and
not an object context. It can, however, access a static property. When getInstance() is called, I check the
Preferences::$instance property. If it is empty, then I create an instance of the Preferences class and
store it in the property. Then I return the instance to the calling code. Because the static getInstance()
method is part of the Preferences class, I have no problem instantiating a Preferences object even
though the constructor is private.
Figure 9-2 shows the Singleton pattern.

Free download pdf