【问题标题】:Is shadowing parent fields in PHP strictly incorrect?PHP中的阴影父字段是否严格不正确?
【发布时间】:2016-08-06 09:18:50
【问题描述】:

PHP 允许隐藏父字段,只要它们派生的访问级别与父级相同或低于父级,如图 1 所示。

图 1

class A {
    protected $x;

    function f() {
        return $this->x;
    }
}

class B extends A {
    protected $x = 'foo';
}

(new B)->f(); // 'foo'

这里使用阴影来利用 PHP 的字段初始化。但是,Php Inspections (EA Extended) 等一些 linter 警告这是错误的,而是建议使用构造函数来初始化字段,如图 2 所示。

图 2

class A {
    protected $x;

    function f() {
        return $this->x;
    }
}

class B extends A {
    function __construct() {
        $this->x = 'foo';
    }
}

(new B)->f(); // 'foo'

通过重写B 的实现以使用构造函数初始化,我们根本不需要使用阴影。

阴影是否严格不正确?如果没有,什么时候应该允许阴影?

【问题讨论】:

    标签: php shadowing


    【解决方案1】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2013-06-30
    • 1970-01-01
    • 2016-12-02
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多