PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


■Note The static keyword was introduced with PHP 5. It cannot be used in PHP 4 scripts.


Static methods are functions with class scope. They cannot themselves access any normal
properties in the class, because these would belong to an object, but they can access static properties. If
you change a static property, all instances of that class are able to access the new value.
Because you access a static element via a class and not an instance, you do not need a variable that
references an object. Instead, you use the class name in conjunction with ::.


print StaticExample::$aNum;
StaticExample::sayHello();


This syntax should be familiar from the previous chapter. I used :: in conjunction with parent to
access an overridden method. Now, as then, I am accessing class rather than object data. Class code can
use the parent keyword to access a superclass without using its class name. To access a static method or
property from within the same class (rather than from a child), I would use the self keyword. self is to
classes what the $this pseudo-variable is to objects. So from outside the StaticExample class, I access
the $aNum property using its class name:


StaticExample::$aNum;


From within the StaticExample class I can use the self keyword:

class StaticExample {
static public $aNum = 0;
static public function sayHello() {
self::$aNum++;
print "hello (".self::$aNum.")\n";
}
}


■Note Making a method call using parent is the only circumstance in which you should use a static reference


to a nonstatic method.


Unless you are accessing an overridden method, you should only ever use :: to access a method or property that


has been explicitly declared static.


In documentation, however, you will often see static syntax used to refer to a method or property. This does not


mean that the item in question is necessarily static, just that it belongs to a certain class. The write() method of


the ShopProductWriter class might be referred to as ShopProductWriter::write(), for example, even though


the write() method is not static. You will see this syntax here when that level of specificity is appropriate.


By definition, static methods are not invoked in the context of an object. For this reason, static
methods and properties are often referred to as class variables and properties.A consequence of this is
you cannot use the $this pseudo-variable inside a static method.

Free download pdf