Analysis of PHP Late Static Binding Instance
- 2021-11-13 00:56:34
- OfStack
This article illustrates the late static binding of PHP. Share it for your reference, as follows:
Beginning with php 5.3, php added a feature called late binding to reference statically called classes within the scope of inheritance
This function is named "late static binding" from the perspective of language interior; "Late binding" means: static:: It is no longer parsed to define the class where the current method is located, but calculated at actual runtime, and can also become "static binding"; Because it can be used (but not limited to static method calls).
Limitations of self::
Use
self::
Or
_class_
Static reference to the current class, depending on the class in which the current method is defined
Examples:
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); //A
Print results:
A
Usage of late static binding
Late static binding attempts to bypass the restriction by introducing a keyword to represent the class originally called at runtime. Simply put, this keyword allows you to refer to B instead of A when you call test () above. It was finally decided not to reference the new keyword, but to use the reserved static keyword
Examples:
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Late static binding starts here
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
The printed result is:
B
The processing method of late static binding solves the static call which has not been solved completely in the past. In the other aspect, if the static call uses parent:: or self::, the call information will be forwarded
<?php
class A {
public static function foo() {
static::who();
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
A::foo();
parent::foo();
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
class C extends B {
public static function who() {
echo __CLASS__."\n";
}
}
C::test();
?>
Print results:
A
C
C
Examples:
<?php
class a {
static public function test() {
print get_called_class();
}
}
class b extends a {
}
a::test();
b::test();
?>
Print results:
a
b
Special statement:
get_called_class()
; Get the name of the class. Call in the static method
For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.