我们应该直接访问受保护的属性还是使用PHP中的getter?
我有两个班,一个是另一个班的女儿.在母亲中,我将某些属性声明为受保护,并为我的属性生成所有getter.所以,我可以直接或通过getter访问和定义这些属性,但我不知道是否有更好的解决方案.
示例:
class Mother {
private $privateProperty;
protected $protectedProperty;
public $publicProperty;
/*** Private property accessors ***/
public function setPrivateProperty($value)
{
$this->privateProperty = $value;
}
public function getPrivateProperty()
{
return $this->privateProperty;
}
/*** Protected property accessors ***/
public function setProtectedProperty($value)
{
$this->protectedProperty = $value;
}
public function getProtectedProperty()
{
return $this->protectedProperty;
}
}
class Child extends Mother {
public function showProtectedProperty() {
return $this->getProtectedProperty(); // This way ?
return $this->protectedProperty; // Or this way ?
}
public function defineProtectedProperty() {
$this->setProtectedProperty('value'); // This way ?
$this->protectedProperty = 'value'; // Or this way ?
}
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我知道我不能直接访问/设置私有属性,并且它对公共属性没用.但我可以使用两种方式来保护受保护的财产.那么,有什么标准可以使用吗?
当您确实在类层次结构中使用 getter 和 setter 时,就可以实现最佳封装。这意味着:属性应该是私有的,并且 getter/setter 应该受到保护(如果不是公共的)。
例如,如果您想要记录对某些属性的访问,想要添加过滤方法或其他检查,如果您只是访问派生类中的这些属性,则整个机制将被删除。
(当然,在某些情况下,您只需将属性公开以使代码更短,并且因为您知道该类实际上只是一个数据持有者......但是,在这种情况下,这些属性仍然不会受到保护,而只是民众)