1 //Traditional Mode--this code works well, but a lot of repetitive code is annoying, don't want to create this same code for each domainobject subclass? 2 /*3 4 abstract class domainobject{}5 6 class User extends DomainObject7 {8 Public function __construct ()9 {Ten echo __method__; One } A - Public static function create () - { the return new self (); - } - - } + class Document extends DomainObject - { + Public function __construct () A { at echo __method__; - } - - Public static function create () - { - return new self (); in } - to } + user::create (); - document::create (); the */ * $ //can you do this? Instantiates the original caller, who invokes the instantiation of WHO. But here self is the abstract class that points to DomainObjectPanax Notoginseng //fatal Error:cannot Instantiate abstract class DomainObject cannot instantiate an abstraction method - /* the Abstract class DomainObject + { A Public static function create () the { + return new self (); - } $ } $ - class User extends domainobject{} - class Document extends domainobject{} the user::create (); - */Wuyi the //after 5.3, you can delay static binding by using the static keyword, and, in common, static is pointing to the original caller - Abstract classDomainObject Wu { - Public Static functionCreate () About { $ return New Static(); - } - } - classUserextendsDomainObject A { + Public function__construct () the { - Echo __method__; $ } the the } the classDocumentextendsDomainObject the { - Public function__construct () in { the Echo __method__; the } About } theUser::create ();//user::__construct theDocument::create ();//document::__construct
The/***********static keyword can be used not only for instantiation, but also for static method invocation identifiers, as with self and parent **************/
1 Abstract classDomainObject2 {3 Private $group;4 Public function__construct ()5 {6 //$this->group = Self::getgroup ();7 $this->group =Static::Getgroup ();8 }9 Ten Public Static functionCreate () One { A return New Static(); - } - the Static functionGetgroup () - { - return' Default '; - } + } - + classUserextendsdomainobject{} A classDocumentextendsDomainObject at { - Static functionGetgroup () - { - return' Document '; - } - } in classSpreadSheetextendsdocument{} - to Print_r(User::create ());//[Group:DomainObject:private] = default + Print_r(Document::create ());//[Group:DomainObject:private] = document - Print_r(Spreadsheet::create ());//[Group:DomainObject:private] = document
php5.3 delay statically binding static keyword