If you are a lazy programmer, you may be annoyed to 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 fine, but a lot of duplicate code can be annoying.
I don't want to add a create method to each subclass, and if you put the Create method in superclass U, the code might be
Abstract class u{
public static function Create () {
return new self ();
}
}
Class U1 extends u{
function A () {}
}
Class U2 extends u{
}
U1::create ();
Look neat and tidy, now we put the common code in one place and use self as a reference to that class. But here we make a hypothesis about self.
In fact, self does not have exactly the same effect on the class as $this does on the object. Self refers not to the calling context, he refers to the parsing context, so if you run the above, you will get
Fatal Error:cannot Instantiate abstract class U in d:wampwwwtestoopstatic.php on line 21
Self is therefore resolved to define the U of Create, rather than to the U1 class that invokes self.
Before php5.3, there were strict restrictions on this, resulting in a number of clumsy solutions, php5.3 introduced deferred static binding and the use of 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 can be used not only as an instantiation, but also as a call identifier for a static method, or even from a non-static context, as Self,parent
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)