我们应该直接访问受保护的属性还是使用
PHP中的getter?
@H_404_12@
当您确实在类层次结构中使用getter和setter时,可以实现最佳封装.这意味着:属性应该是私有的,getter / setter是受保护的(如果不是公共的).
我有两个班,一个是另一个班的女儿.在母亲中,我将某些属性声明为受保护,并为我的属性生成所有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 ? } }
在这个例子中,我知道我不能直接访问/设置私有属性,并且它对公共属性没用.但我可以使用两种方式来保护受保护的财产.那么,有什么标准可以使用吗?
例如,如果要记录对某些属性的访问权限,想要添加过滤器方法或其他检查,则只要在派生类中访问这些属性,就会删除整个机制.
(当然,在某些情况下,您只需将属性公开以使代码更短,并且因为您知道该类实际上只是数据持有者……但是,在这种情况下,这些属性仍然不会受到保护,而只是简单上市)