在PHP中,为什么我能够以静态方式访问非静态方法?

Vee*_*hoo 8 php static

在以下代码中,nonStatic()不是静态方法.即使这样,我也能够在不创建对象的情况下(以静态方式)访问它.任何人都可以帮助我理解,因为这在Java等其他语言中是不可能的吗?

<?php
class MyClass
{
    function nonStatic() {
        echo "This can be printed";
    }
}
MyClass::nonStatic(); // This can be printed
Run Code Online (Sandbox Code Playgroud)

Ja͢*_*͢ck 6

这是允许的,会产生E_STRICT警告:

Error #: 2048, Error: Non-static method MyClass::nonStatic() should not be called statically, assuming $this from incompatible context
Run Code Online (Sandbox Code Playgroud)

在PHP的早期OO实现中,这是默默允许的,但是后来采用了更好的实践.

相反的工作没有任何障碍:

class Test
{
    function foo()
    {
        echo $this->bar();
    }

    static function bar()
    {
        return "Hello world\n";
    }
}

$x = new Test;
$x->foo();
Run Code Online (Sandbox Code Playgroud)

这打印Hello world.


Por*_*ear 0

不确定,可能是一些 PHP 魔法(有时有点像那样),但你不应该这样做。

在这里阅读更多内容http://php.net/manual/en/language.oop5.static.php

他们还展示了类似的示例,但请注意:

静态调用非静态方法会生成 E_STRICT 级别警告,这意味着这种神奇的能力可能会在未来版本中消失。所以不要这样做:)