php static 和self区别
static(关键字) 类似于 self(关键字) , 但它指向的是被调用的类(Document) 而不是包含类(DomainObject) , static 和 self 的区别:
<?php class DomainObject{ public static function createStatic(){ return new static(); } public static function createSelf(){ return new self(); } } class User extends DomainObject{ } class Document extends DomainObject{ } echo '<pre>'; var_dump( Document::createStatic()); var_dump( Document::createSelf()); Result: object(Document)[1] object(DomainObject)[1]
以前你这么写:
abstract class DomainObject{ } class User extends DomainObject{ public static function create(){ return new User(); } } class Document extends DomainObject{ public static function create(){ return new Document(); } }
现在这么写
abstract class DomainObject{ public static function create(){ return new static(); } } class User extends DomainObject{ } class Document extends DomainObject{ }
好处: 可以节省大量重复代码~