关于伪变量的一段示例代码在PHP5.6和7.0下运行结果不同?
阿神
阿神 2017-04-11 09:51:48
[PHP讨论组]

在翻看 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)
大家讲道理

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();
?>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号