我们应该直接访问受保护的属性还是使用
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 ?
}
}
在这个例子中,我知道我不能直接访问/设置私有属性,并且它对公共属性没用.但我可以使用两种方式来保护受保护的财产.那么,有什么标准可以使用吗?