如果到现在我对ststic有点了解现在我意识到我什么都不懂.我很困惑,我很难理解,我不能.有人可以在使用self,parent,static时解释这个程序,以及我所做的所有最小的改变都会改变结果而不会让我无法理解正在发生的事情.非常感谢 ..
来自http://docs.php.net/language.oop5.late-static-bindings的代码
<?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();
?>
Run Code Online (Sandbox Code Playgroud)
出局是:
A
C
C
Run Code Online (Sandbox Code Playgroud)
web*_*ave 22
您需要了解Late Static Binding的概念,它决定了何时将标识符绑定到代码/数据.您可以告诉PHP早期(self::)或稍后(static::)绑定它.
将示例减少到两个类我们得到:
class A {
public static function foo() {
self::who(); // PHP binds this to A::who() right away
static::who(); // PHP waits to resolve this (hence, late)!
}
public static function who() {
echo __CLASS__."\n";
}
}
class B extends A {
public static function test() {
self::foo();
}
public static function who() {
echo __CLASS__."\n";
}
}
B::test();
Run Code Online (Sandbox Code Playgroud)
请查看http://php.net/manual/en/language.oop5.static.php.它说:
将类属性或方法声明为静态可使它们无需实例化类的实现.
...
因为静态方法可以在没有创建对象实例的情况下调用,所以伪变量$ this在声明为static的方法中不可用.
你不能使用$this因为在调用静态方法时,没有实例化的类对象放在$this变量中.所以你用self::.
parent::指的是当前类正在扩展的父类.例如,对于C类,父类是B类,而对于B类,父类是A类.请参阅http://php.net/manual/en/keyword.parent.php.
如果希望在不实际声明该类的实例的情况下访问该函数,则可以使用静态方法.
仔细检查您的问题后,您的链接指向Late Static Bindings.该页面中的前两个示例非常清楚地表明需要static::语法,但要澄清您发布的示例:
看看foo()A类中的方法.它调用static::who().这意味着该方法who()将在调用该函数的类的范围内调用,而不是在定义函数的类的范围内调用.所以,如果你打电话C::foo(),它会回应C.
相反,如果它被调用self::who(),它将调用A::who().因为在A类中,self::指的是A.
希望这会有所帮助.
答案的关键是static :: who(),记得static ::意味着你用实际的类调用方法(在我们的例子中是C).
所以C :: test()运行如下:
A::foo(); -> calls to A::foo() therefor echo A
parent::foo(); -> calls to C parent (which is B), B::foo() inherits A::foo() which calls to static::who(), but our actual class is C, therefor echo C
self::foo(); -> again calls to foo() which calls to static::who() with our actual class C
Run Code Online (Sandbox Code Playgroud)
如果不是static :: who()foo正在调用self :: who(),那么你将获得三个A.