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

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

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

解决方案

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

这篇关于关于伪变量的一段示例代码在PHP5.6和7.0下运行结果不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆