我有一个父对象,用于我的应用程序中的一般 CRUD - 它具有基本的保存和检索方法,因此我不必将它们重新包含在我的所有对象中。我的大多数子对象都扩展了这个基础对象。这工作正常,但我发现检索序列化子对象时出现问题。我在创建子实例的父对象中使用“检索”方法,然后从未序列化的子对象的属性填充自身 - 这意味着可以“自行反序列化”对象。
唯一的问题是 - 如果子对象具有 protected 或私有(private)属性,则父对象无法读取它,因此在检索过程中不会获取它。
所以我正在寻找一种更好的“ self 反序列化”方法,或者一种允许父对象“查看” protected 属性的方法——但仅限于在检索过程中。
代码示例:
BaseObject {
protected $someparentProperty;
public function retrieve() {
$serialized = file_get_contents(SOME_FILENAME);
$temp = unserialize($serialized);
foreach($temp as $propertyName => $propertyValue) {
$this->$propertyName = $propertyValue;
}
}
public function save() {
file_put_contents(SOME_FILENAME, serialize($this));
}
}
class ChildObject extends BaseObject {
private $unretrievableProperty;
public setProp($val) {
$this->unretrivableProperty = $val;
}
}
$tester = new ChildObject();
$tester->setProp("test");
$tester->save();
$cleanTester = new ChildObject();
$cleanTester->retrieve();
// $cleanTester->unretrievableProperty will not be set
已编辑:应该说“私有(private)”不 protected 子属性。
最佳答案
像这样尝试:
abstract class ParentClass
{
protected abstract function GetChildProperty();
public function main()
{
$value = $this->GetChildProperty();
}
}
class ChildClass extends ParentClass
{
private $priv_prop = "somevalue";
protected function GetChildProperty()
{
return $this->priv_prop;
}
}
关于PHP 在父级访问子级的私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3484165/