通过范围解析运算符调用非静态方法

Invoking a non-static method via the scope resolution operator

found PHP 解释器有一些奇怪的(对我来说)行为,我不确定在生产中使用它是否安全。

当我们调用Foo::bar()并且Foo class没有静态bar方法但它有非静态bar方法时,解释器将在 null 上调用非静态 bar (是的,这听起来很荒谬)。我希望在这种情况下调用 __callStatic。但由于某种原因,这不是正在发生的事情。

然后我找到了这种行为的便捷用法:为 class 提供具有相同名称的静态和非静态方法,如下所示:

class Foo
{
    public function bar(){
        if (isset($this)) {
            $this->nonStaticBar();
        } else {
            static::staticBar();
        }
    }

    private function nonStaticBar() {
        echo "Non-static\n";
    }

    private static function staticBar() {
        echo "Static\n";
    }
}

(new Foo())->bar(); // Output: "Non-static"
Foo::bar(); // Output: "Static"

是的,我知道,这种方法并不优雅,而且在架构上是错误的。问题是使用这个 "feature" 是否安全(符合标准)。还有其他情况 isset($this) 可以等于 false 吗?

虽然您上面的示例确实有效,但这不是最佳做法。 这在 PHP 文档 here 中得到认可,并指出在版本 7 之前的 PHP 版本中,如果启用了 E_STRICT 错误报告,那么它将发出错误:

Strict Standards: Non-static method Foo::bar() should not be called statically in /Path/to/file.php on line 22

此外,在 PHP 版本 7 及更高版本中,静态调用静态函数已被弃用,并且会在执行时导致以下错误:

Deprecated:  Non-static method Foo::bar() should not be called statically in /Path/to/file.php on line 22