Working with scenes
First look at the following code:
Abstract class Base {
//do sth
}
class AClass extends base{public
static function create () {return
n EW AClass ();
}
Class Bclass extends base{public
static function create () {return
new Bclass ();
}
}
Var_dump (Aclass::create ());
Var_dump (Bclass::create ());
Output:
Object (aclass) #1 (0) {} object (Bclass) #1 (0) {}
The above AClass and bclass inherit from the base abstract class, but the static method of Create () is implemented at the same time in two subclasses. Following OOP, this repetitive code should be implemented in the parent class of base.
Improved code
Abstract class Base {public
static function create () {return
new self ();
}
}
Class AClass extends base{
}
class Bclass extends base{
}
var_dump (Aclass::create ());
Var_dump (Bclass::create ());
Now that the code seems to have met our previous idea of putting the Create () method together in the parent class, let's run the next to see what happens.
Cannot instantiate abstract class base in ...
Unfortunately, the code does not seem to run as we expected, and self () in the parent class is parsed into the base parent class, not inheriting from his subclass. So in order to solve this problem, the concept of delayed static binding is introduced in php5.3.
Delay Static binding
Abstract class Base {public
static function create () {return
new static ();
}
}
Class AClass extends base{
}
class Bclass extends base{
}
var_dump (Aclass::create ());
Var_dump (Bclass::create ());
This code is almost identical to the previous one, except that the self is replaced with the static keyword, static resolves to subclasses, not the parent class, which solves the problem that is encountered above, which is the delayed static binding of PHP.
Finally, run the code and get the results you want.
Object (aclass) #1 (0) {} object (Bclass) #1 (0) {}