2012-03-25 91 views
0

问题很简单。我有一个基本的抽象类(人)。从这我扩大了另一类(患者)。php阻止父母访问儿童属性

我在PERSONS表中保存个人信息(例如名字,姓氏)[有ADD函数。 ]。患者特定信息(如疾病,药品等)被保存到单独的患者类别中。 [有一个ADD函数调用父代,然后是一些代码]。

我该如何防止人员的添加功能访问它的孩子,患者内定义的属性?

为了更清楚,这里是一个示例代码:

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' ; 
} 

然后当我打电话添加的$insertables将包含P_var,CH_var1,CH_var2。我只希望它有P_var。

感谢

+0

如果'patient'属性不是'public',那么父类将无法看到它们。 – 2012-03-25 15:35:31

+0

在这种情况下,是否有无论如何我都可以使用'person'对象只有没有孩子提供的添加剂? – 2012-03-25 15:38:15

+0

您需要发布更多的代码,以便我们可以看到您的类实现。子类不会将任何添加的东西传递给父类, d如果父项是'abstract',则它不能被自身实例化。 – 2012-03-25 15:41:51

回答

1

您可以通过使用反射(见http://www.php.net/manual/en/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; 
    } 
} 

不过,我建议重构你的代码,而不是得到一个清晰的解决方案(例如,添加一个方法getProperties()(可能通过一个接口定义)或什么的。然后让你的数据库类中调用该函数以获取列表

+0

谢谢。我正在为此工作。 – 2012-03-25 16:42:47

+0

你能详细说一下,我应该在哪里放?父抽象类中的函数? – 2012-03-25 18:05:53

+0

我已经更新了我的答案中的代码! – Niko 2012-03-25 18:14:53