Home > Article > Backend Development > What is php delayed static binding? Detailed explanation of delayed static binding example code
php delayed static binding: refers to the self of the class, which is not based on the time of definition, but based on the running results during calculation.
(1) When the subclass instantiated object $stu calls the say method, it runs in the parent class Human, so self::hei() in say() is the hei() of the parent class. )method.
(2) static::method name(): If you use the static keyword, you will first search for the method in the subclass; if not found, search it in the parent class.
Usage scenarios
First observe the following code:
##
abstract class base { //do sth } class aClass extends base{ public static function create(){ return new 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 abstract class base, but the static method create() is also implemented in the two subclasses. Following the oop idea, this repetitive code should be implemented in the parent class 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());The current code seems to be in line with our previous ideas, and the create() method is shared in the parent class. So let's run it and see what happens. Cannot instantiate abstract class base in...
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 the same as the previous one. The difference is that self is replaced with the static keyword, and static will be parsed As a subclass instead of a parent class, this can solve the problems encountered above. This is PHP's delayed static binding. Finally, run the code and get the final desired result.
object(aClass)#1 (0) { } object(bClass)#1 (0) { }
The above is the detailed content of What is php delayed static binding? Detailed explanation of delayed static binding example code. For more information, please follow other related articles on the PHP Chinese website!