2010-11-08 42 views
10

我知道self::staticFunctionName()parent::staticFunctionName()是什么,它们是如何彼此不同以及从$this->functionNamestatic :: staticFunctionName()

但什么是static::staticFunctionName()

+0

*(相关)* [这是什么符号在PHP中的意思](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon 2010-11-08 08:04:20

回答

15

这是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(); 

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(); 

static作为此行为的关键字是一种令人困惑,因为这一切都不过。 :)

+1

你如果你在父类中,使用static :: functionName(),但你想调用孩子的静态函数。这样你可以让子类覆盖静态行为。 – 2010-11-08 01:56:07