Home  >  Q&A  >  body text

关于伪变量的一段示例代码在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 下切换版本运行的,也在一个代码在线运行网站运行代码,也是这个结果。

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

阿神阿神2638 days ago535

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-04-11 09:53:48

    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();
    ?>

    reply
    0
  • Cancelreply