PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 4 ■ ADVANCED FEATURES


}


class User extends DomainObject {
}


class Document extends DomainObject {
}


print_r(Document::create());


Document Object
(
)


The static keyword can be used for more than just instantiation. Like self and parent, it can be
used as an identifier for static method calls, even from a non-static context. Let’s say I want to include
the concept of a group for my DomainObjects. By default, all classes fall into category 'default', but I’d
like to be able override this for some branches of my inheritance hierarchy:


abstract class DomainObject {
private $group;
public function __construct() {
$this->group = static::getGroup();
}


public static function create() {
return new static();
}


static function getGroup() {
return "default";
}
}


class User extends DomainObject {
}


class Document extends DomainObject {
static function getGroup() {
return "document";
}
}


class SpreadSheet extends Document {
}


print_r(User::create());
print_r(SpreadSheet::create());


I introduced a constructor to the DomainObject class. It uses the static keyword to invoke a static
method: getGroup(). DomainObject provides the default implementation, but Document overrides it. I
also created a new class SpreadSheet that extends Document. Here’s the output:

Free download pdf