静:: staticFunctionName()

she*_*iel 10 php

我知道它们是什么self::staticFunctionName(),parent::staticFunctionName()是什么,以及它们之间是如何不同的$this->functionName.

但是什么static::staticFunctionName()呢?

dec*_*eze 16

它是PHP 5.3+中用于调用后期静态绑定的关键字.
阅读手册中的所有内容:http://php.net/manual/en/language.oop5.late-static-bindings.php


总之,static::foo()工作就像一个动态self::foo().

class A {
    static function foo() {
        // This will be executed.
    }
    static function bar() {
        self::foo();
    }
}

class B extends A {
    static function foo() {
        // This will not be executed.
        // The above self::foo() refers to A::foo().
    }
}

B::bar();
Run Code Online (Sandbox Code Playgroud)

static 解决了这个问题:

class A {
    static function foo() {
        // This is overridden in the child class.
    }
    static function bar() {
        static::foo();
    }
}

class B extends A {
    static function foo() {
        // This will be executed.
        // static::foo() is bound late.
    }
}

B::bar();
Run Code Online (Sandbox Code Playgroud)

static作为这种行为的关键词有点令人困惑,因为它只是.:)

  • 如果您在父类中,则使用static :: functionName(),但是您想要调用子函数的静态函数.这样你就可以让子类覆盖静态行为. (2认同)