正如Baba已经指出的那样,它会导致取决于您的配置。E_STRICT
但是,即使这对你来说没有问题,我认为值得一提的是,以非静态方式调用静态方法可能会导致的一些陷阱。
如果您有一个类层次结构,例如
class A {
public static function sayHello() {
echo "Hello from A!\n";
}
public function sayHelloNonStaticWithSelf() {
return self::sayHello();
}
public function sayHelloNonStaticWithStatic() {
return static::sayHello();
}
}
class B extends A {
public static function sayHello() {
echo "Hello from B!\n";
}
public function callHelloInMultipleDifferentWays() {
A::sayHello();
B::sayHello();
$this->sayHelloNonStaticWithSelf();
$this->sayHelloNonStaticWithStatic();
$this->sayHello();
}
}
$b = new B();
$b->callHelloInMultipleDifferentWays();
这将生成以下输出:
Hello from A!
// A::sayHello() - obvious
Hello from B!
// B::sayHello() - obvious
Hello from A!
// $this->sayHelloNonStaticWithSelf()
// self alweays refers to the class it is used in
Hello from B!
// $this->sayHelloNonStaticWithStatic()
// static always refers to the class it is called from at runtime
Hello from B!
// $this->sayHello() - obvious
如您所见,在混合静态和非静态方法调用和技术时,很容易实现意外行为。
因此,我的建议也是:使用 Class::method 显式调用你想要调用的静态方法。或者更好的是,不要使用静态方法,因为它们会使你的代码无法测试。