简体   繁体   English

父级的php设置值

[英]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. 它说我在UserEvent类中有一些声明为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM