简体   繁体   English

php防止父级访问子级属性

[英]php prevent parent from accessing child properties

the question is simple. 问题很简单。 I have a base abstract class (person). 我有一个基本的抽象类(人)。 From this i have extended another class (patients). 由此,我扩展了另一类(患者)。

I save personal information (eg firstname, lastname) in PERSONS table [there is an ADD function. 我将个人信息(例如名字,姓氏)保存在PERSONS表中[存在ADD函数。 ]. ]。 Patient specific information (like illness, medicines, ...) are saved into a separate PATIENTS class. 患者特定信息(例如疾病,药物等)被保存到单独的PATIENTS类中。 [there is an ADD function that calls the parent, then some code]. [有一个调用父级的ADD函数,然后是一些代码]。

How do I prevent person's add function from accessing properties defined inside it's child, patients? 如何防止人的add函数访问在其孩子,患者内部定义的属性?

In order to make it more clear, here is a sample code: 为了更清楚,这里是一个示例代码:

class P {
public P_var = 'Anoush' ; 
public function add ()
{
  // find all properties:
  foreach ($this as $prop => $val )
  {
     $insertables [$prop] = $val ; 
  }
  // insert all VALUES FIELDSET etc. based on the array created above 

}

class CH extends P {
public CH_var1 = 'ravan' ; 
public CH_var2 = 'something' ; 
}

Then when I call add, the $insertables will contain P_var, CH_var1 , CH_var2. 然后,当我调用add时, $insertables将包含P_var,CH_var1,CH_var2。 I only want it to have P_var. 我只希望它具有P_var。

Thanks 谢谢

You can do this by using Reflection (see http://www.php.net/manual/en/book.reflection.php ). 您可以通过使用Reflection实现(请参阅http://www.php.net/manual/zh/book.reflection.php )。

class Parent {
    public function add() {
        $insertables = $this->_getOwnProperties(__CLASS__);
        // ...
    }

    protected function _getOwnProperties($className) {
        $reflection = new ReflectionClass($this);
        $props = array();

        foreach ($reflection->getProperties() as $name => $prop) {
            if ($prop->class == $className) {
                $props[$name] = $prop;
            }
        }

        return $props;
    }
}

However, I recommend refactoring your code instead to get a cleaner solution (eg add a method getProperties() (maybe defined by an interface) or whatever. Then let your database class invoke that function in order to get the list of properties to store in the database. 但是,我建议您重构代码,以获得更简洁的解决方案(例如,添加方法getProperties() (可能由接口定义)等),然后让您的数据库类调用该函数以获取要存储的属性列表数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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