将属性从类传递到基类


Passing properties from class to base class

在我的程序中,一个对象表示数据库中的一行,它具有所有相同的数据和setters和getters等。

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

class Person extends Base {
  protected $name;
  protected $age;
  /* Setters & Getters */
}

在基类上,我有一个 Save() 方法,该方法将从 Person 类的属性中创建一个更新查询。我在弄清楚如何将属性传递给 Base 的 Save() 方法时遇到了麻烦。我心目中很少,但我对他们不太满意。

1.为所有属性添加前缀。比如"db_":

protected $db_id;
protected $db_age;
Loop get_object_vars($this) and check the prefix.
  • 混乱

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

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).
  • 无法为其他内容添加属性

还有其他方法可以做到这一点吗?

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

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