我正试图了解后期静态绑定,通过阅读几个堆栈溢出问题和手册,我发现了其他问题。我不明白为什么在我找到的所有示例(包括手册)中,直接呼应类名的方法在子类中重复。
我的理解是,从另一个类扩展的类继承了其父类的所有方法和属性。因此,为什么who()方法在后期静态绑定的PHP手动示例中重复。我意识到,如果没有它,家长班会得到回应,但我不明白为什么。
请参阅手册中的代码。。。
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
?>
为什么需要重写who()方法,而我认为它必须是相同的?提前谢谢。
Late static binding
类似于虚拟方法调用,但它是静态的。
在类A中,方法测试调用two()。two()必须显示"A"。然而,因为这类似于虚拟方法,所以改为执行B::two()
。
下面是几乎相同的代码,但我相信更清楚的是发生了什么:
<?php
class A {
public static function process() {
echo "AAAA";
}
public static function test() {
static::process(); // Here comes Late Static Bindings
}
}
class B extends A {
public static function process() {
echo "BBBB";
}
}
B::test();
它在执行时打印CCD_ 3。