【发布时间】:2011-06-04 15:14:14
【问题描述】:
我正在寻找这个已经有一段时间了。 我看到很少有类似的问题,但不确定它们是否适用于教义2 和这个问题。 我正在尝试开始使用 CodeIgniter2 和 Doctrine2,但我遇到了一些问题,我不是 php 中的 OOP 专家。 我想要包含 CRUD 和其他少数方法的 MainObject,并且我希望对象扩展该类并使用父类的方法,但具有子类的属性。由于 Doctrine2 使用对象的私有属性,我无法从父类访问这些方法。例如:
Class MainObject{
public function validateFields(){
//go over each field and validate/update if needed
}
public function store(){
// do some validation, some logic, store, etc...
}
}
Class User extends MainObject{
/**
* @Column(type="string", length=32, unique=true, nullable=false)
*/
private $username;
/**
* @Column(type="string", length=64, nullable=true)
*/
private $email;
}
现在,我想打电话
$user = new User();
//set properties, somehow
$user-__set($something);
//call validation or store or some method from the parent that will interact with child properties
$user->validate();
$user->store();
$user->uploadImage();
$user->formatPropertiesForSomethingSpecial();
我几乎可以通过使用 ReflectionClass 来做到这一点,但我不确定我这样做的方式是否正确? 或者有没有办法让 MainObject 使用所有这些方法,然后将 User 传递给它,这样它就可以对用户做它应该做的事情,这可能是“更正确”的方法吗?我认为它不允许我对用户的 Private 属性做一些事情,但我猜 User 可以有自己的 getter 和 setter?
多年来,我一直在 php 中使用 semi-oop,但这对我来说是新事物,因此感谢您提供任何建议、教程、网址、评论等任何内容。
【问题讨论】:
标签: php inheritance properties parent-child visibility