将属性从类传递到基类

时间:2013-11-02 20:51:53

标签: php oop properties

在我的程序中,一个对象代表数据库中的一行,它具有所有相同的数据和setter&吸气等。

每列的值都保存到对象中的属性中。例如:

class Person extends Base {
  protected $name;
  protected $age;

  /* Setters & Getters */
}

在Base类上,我有一个Save()方法,它将从Person类的属性中创建更新查询。我无法弄清楚如何将属性传递给Base的Save()方法。我心里很少,但我对他们不太满意。

1。 为所有属性添加前缀。像“db _”:

protected $db_id;
protected $db_age;

Loop get_object_vars($this) and check the prefix.
  • 混淆

2。 添加一个数组,其中包含与数据库中的行相关的所有属性名称

protected $db_properties = array("id", "age");
protected $id;
protected $age;

Loop get_object_vars($this) and check if they are in the $db_properties array.
Or loop the $db_properties and get the properties.
  • 双重相同数据

3。 假设所有属性始终与数据库中的行相关。

Loop get_object_vars($this).
  • 无法为其他内容添加属性

还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

我不确定我是否明白这个问题,但你考虑过字典吗? http://us2.php.net/manual/en/language.types.array.php

答案 1 :(得分:0)

为什么你需要把它传回Base?实例化Person时,Base成为其中的一部分。因此,如果Base定义了变量,Person也将拥有该变量。

相关问题