【发布时间】: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 的实现以使用构造函数初始化,我们根本不需要使用阴影。
阴影是否严格不正确?如果没有,什么时候应该允许阴影?
【问题讨论】: