本文介绍了PHP中的后期静态绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关LSB功能的php手册,我了解它在静态上下文中的工作方式,但是我在非静态上下文中不太了解它.手册中的示例是这样的:

I am reading the php manual about the LSB feature, I understand how it works in the static context, but I don't quite understand it in the non-static context. The example in the manual is this:

<?php
class A {
    private function foo() {
        echo "success!\n";
    }
    public function test() {
        $this->foo();
        static::foo();
    }
}

class B extends A {
   /* foo() will be copied to B, hence its scope will still be A and
    * the call be successful */
}

class C extends A {
    private function foo() {
        /* original method is replaced; the scope of the new one is C */
    }
}

$b = new B();
$b->test();
$c = new C();
$c->test();   //fails
?>

输出是这样的:

success!
success!
success!


Fatal error:  Call to private method C::foo() from context 'A' in /tmp/test.php on line 9

对于类B,我不了解,如何将A中的私有方法继承到B?谁能引导我了解这里发生的事情?非常感谢!

I do not understand for class B, how a private method in A could be inherited to B? Can anyone walk me through what is going on here? Many thanks!

推荐答案

使用后期静态绑定只会更改为调用选择的方法.选择该方法后,将应用可见性规则来确定是否可以调用它.

The use of late static binding only changes the method that gets chosen for the call. Once the method is chosen, visibility rules are applied to determine whether or not it may be called.

对于BA::test查找并调用A::foo. B中的注释不正确-foo未复制到B.由于它是私有的,因此只能从A中的其他方法(如A::test)进行调用.

For B, A::test finds and calls A::foo. The comment in B isn't correct--foo isn't copied to B. Since it's private, it is only callable from other methods in A such as A::test.

C失败,因为后期的静态绑定机制找到了 new 私有方法C::foo,但是A的方法无权访问它.

C fails because the late static binding mechanism locates the new private method C::foo, but A's methods don't have access to it.

我建议您为静态字段和方法保留后期静态绑定,以免造成混淆.

I recommended that you reserve late static binding for static fields and methods to avoid confusion.

这篇关于PHP中的后期静态绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 02:16