1 //传统模式 --这段代码能很好工作,但大量的重复代码很烦人,不想为每个DomainObject子类都创建这段相同代码吧?
 2 /*
 3 
 4 abstract class DomainObject{}
 5 
 6 class User extends DomainObject
 7 {
 8     public function __construct()
 9     {
10         echo __METHOD__;
11     }
12     
13     public static function create()
14     {
15         return new self(); 
16     }
17 
18 }
19 class Document extends DomainObject
20 {
21     public function __construct()
22     {
23         echo __METHOD__;
24     }
25     
26     public static function create()
27     {
28         return new self(); 
29     }
30 
31 }
32 User::create();
33 Document::create();
34 */
35 
36 //能否这么干? 实例化最初调用者,谁调用实例化谁。但是这里self是指向的抽象类DomainObject
37 //fatal error: Cannot instantiate abstract class DomainObject 无法实例化抽象方法
38 /*
39 abstract class DomainObject
40 {
41     public static function create()
42     {
43         return new self();
44     }    
45 }
46 
47 class User extends DomainObject{}
48 class Document extends DomainObject{}
49 User::create(); 
50 */
51 
52 //5.3后 可以使用static关键字,延迟静态绑定,通俗的就是,static 指向的是最初调用者
53 abstract class DomainObject
54 {
55     public static function create()
56     {
57         return new static();
58     }    
59 }
60 class User extends DomainObject
61 {
62     public function __construct()
63     {
64         echo __METHOD__;
65     }
66     
67 }
68 class Document extends DomainObject
69 {
70 public function __construct()
71     {
72         echo __METHOD__;
73     }
74 }
75 User::create(); //User::__construct
76 Document::create();  //Document::__construct

 /***********static 关键字不仅仅可以用于实例化,和self和parent一样,static还可以作为静态方法调用标识符**************/

 1 abstract class DomainObject
 2 {
 3     private $group;
 4     public function __construct()
 5     {
 6         //$this->group = self::getGroup();
 7         $this->group = static::getGroup();
 8     }
 9     
10     public static function create()
11     {
12         return new static();
13     }
14     
15     static function getGroup()
16     {
17         return 'default';
18     }
19 }
20 
21 class User extends DomainObject{}
22 class Document extends DomainObject
23 {
24     static function getGroup()
25     {
26         return 'document';
27     }
28 }
29 class SpreadSheet extends Document{}
30 
31 print_r(User::create());         //     [group:DomainObject:private] => default
32 print_r(Document::create());     //     [group:DomainObject:private] => document
33 print_r(SpreadSheet::create());  //     [group:DomainObject:private] => document

 

posted on 2016-05-12 21:05  睡着的糖葫芦  阅读(220)  评论(0编辑  收藏  举报