正如 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显式调用您要调用的静态方法。甚至最好不要使用静态方法,因为它们会使您的代码不可测试。