[英]php setting values at parent level
I have a User
class extending an Id
abstract class. 我有一个
User
类,扩展了一个Id
抽象类。 Somehow I will introduce another class called Event
extending the Id
class too. 我将以某种方式引入另一个称为
Event
的类,以扩展Id
类。 The __construct()
methods are very similar, so I want to put the constructor code in the Id
class. __construct()
方法非常相似,因此我想将构造函数代码放在Id
类中。
Here is my __construct()
method: 这是我的
__construct()
方法:
class Event extends Id
{
public function __construct($id, $object){
$this->id = $id;
foreach($object as $property => $value) {
if (property_exists($this, $property)) $this->$property = $value;
}
}
}
class User extends Id
{
public function __construct($id, $object){
$this->id = $id;
foreach($object as $property => $value) {
if (property_exists($this, $property)) $this->$property = $value;
}
}
}
However, if I put the method in the Id
class, PHP warns me at $this->$property = $value;
但是,如果将方法放在
Id
类中,PHP会在$this->$property = $value;
this- $this->$property = $value;
警告我$this->$property = $value;
. 。 It says that I have some attributes stated
private
in the User
or Event
class so that it cannot be initiated in Id
class. 它说我在
User
或Event
类中有一些声明为private
属性,因此无法在Id
类中启动它。
What I want is to reuse my code while keeping those variables private
(because I do not want other except parent class to access them!) 我想要的是重用我的代码,同时保留这些变量的
private
(因为除了父类之外,我不希望其他变量访问它们!)
Some options: 一些选项:
Use protected
variables 使用
protected
变量
You could use Reflection to cheat and set private variables. 您可以使用反射来作弊并设置私有变量。
Use traits (5.4) to import a common __construct
使用特征(5.4)导入通用的
__construct
Refactor a bit. 重构一点。 eg, have a
setProperty
in the child classes that the parent calls, or implement __set
, etc 例如,在父级调用的子级中具有
setProperty
,或实现__set
,等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.