关于伪变量的一段示例代码在PHP5.6和7.0下运行结果不同?

新手上路,请多包涵

在翻看 PHP 手册的时候看到关于伪变量的内容,其中有一份示例代码:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

5.6.30 版本下运行结果是

$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.

7.0.9 版本下运行结果是

$this is defined (A)
$this is not defined.
$this is not defined.
$this is not defined.

我是在 PHPStorm 下切换版本运行的,也在一个代码在线运行网站运行代码,也是这个结果。

有了解的同学解答一下吗?谢谢!

阅读 1.8k
1 个回答

http://php.net/manual/zh/migr...

从不匹配的上下文发起调用

在不匹配的上下文中以静态方式调用非静态方法, 在 PHP 5.6 中已经废弃, 但是在 PHP 7.0 中, 会导致被调用方法中未定义 $this 变量,以及此行为已经废弃的警告。

<?php
class A {
    public function test() { var_dump($this); }
}

// 注意:并没有从类 A 继承
class B {
    public function callNonStaticMethodOfA() { A::test(); }
}

(new B)->callNonStaticMethodOfA();
?>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题