If you are a lazy programmer, you may be annoyed when you see the following code:
Abstract class U {
}
Class u1 extends U {
Public static function create (){
Return new u1 ();
}
}
Class u2 extends U {
Public static function create (){
Return new u2 ();
}
}
This code works normally, but it is annoying to have a lot of repeated code.
I don't want to add the create method to each subclass. If you put the create method in the superclass U, the Code may be
Abstract class U {
Public static function create (){
Return new self ();
}
}
Class u1 extends U {
Function (){}
}
Class u2 extends U {
}
U1: create ();
It looks elegant and neat. Now we place common code in one place and use self as a reference to this class. But here we make a hypothesis for self.
In fact, the role of self on this class is not exactly the same as that of $ this on the object. Self is not the call context, but the parsing context. Therefore, if you run the preceding column, you will get
Fatal error: Cannot instantiate abstract class U in D: \ wamp \ www \ test \ oop \ static. php on line 21
Therefore, self is resolved to the u1 class that defines create rather than the u1 class that calls self.
Before php5.3, there were strict restrictions in this regard and many clumsy solutions were created. php5.3 introduced delayed static binding and the keyword static
Static is similar to self, but it refers to the called class rather than the containing class.
In the following example, u1: create will generate the u1 object instead of instantiating the U object.
Abstract class U {
Public static function create (){
Return new static ();
}
}
Class u1 extends U {
}
Class u2 extends U {
}
U1: create ();
Static not only can be used for instantiation, but can also be used as the call identifier of static methods like self and parent, or even called from a non-static Context
Abstract class U {
Private $ group;
Public function _ construct (){
$ This-> group = static: getGroup ();
}
Public static function create (){
Return new static ();
}
Static function getGroup (){
Return 'default ';
}
}
Class u1 extends U {
}
Class u2 extends U {
Static function getGroup (){
Return 'u2 ';
}
}
Class u3 extends u2 {
}
Print_r (u1: create ());
Echo'
';
Print_r (u3: create ());
U1 Object ([group: U: private] => default)
U3 Object ([group: U: private] => u2)