【发布时间】:2014-06-11 12:50:06
【问题描述】:
我在类继承方面遇到了一些困难。我有 5 个类,所有这些类都使用创建、更新和删除方法访问我的数据库,这些方法我已经抽象化,以便我可以将它们推送到 MasterDatabase 类中,然后让它们都扩展这个类。我遇到的问题是基本继承概念。我浏览了 SOF,很多人都问过类似的问题,但不是这个问题。
class DatabaseMaster {
public function create() {
$attributes = $this->attributes();
$question_marks = array();
foreach ($attributes as $key => $value) {
$question_marks[] = "?";
}
$place_holder = array_intersect_key($attributes, get_object_vars($this));
$place_holder = array_values($place_holder);
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES (";
$sql .= join(", ", array_values($question_marks));
$sql .= ")";
$query = $handler->prepare($sql);
$query->execute($place_holder);
}
}
现在,如果我有一个类用户。我希望这个扩展DatabaseMaster,我想它不能像上面那样继承这个create函数?例如,我的问题是我在方法中对 $this->attributes 的引用。 DatabaseMaster 没有属性,但我的 User 类当然有。如果我运行 $user->create();它不起作用,我认为是因为这个。如何克服这个问题?对于目前过度使用 SOF,我深表歉意!
这行得通....
public function create() {
$attributes = $this->attributes();
$question_marks = array();
foreach ($attributes as $key => $value) {
$question_marks[] = "?";
}
$place_holder = array_intersect_key($attributes, get_object_vars($this));
$place_holder = array_values($place_holder);
$sql = "INSERT INTO users (";
$sql .= join(", ", array_keys($attributes));
$sql .= ") VALUES (";
$sql .= join(", ", array_values($question_marks));
$sql .= ")";
$query = $handler->prepare($sql);
$query->execute($place_holder);
}
所以我的问题很明显......如何在方法中使表名动态化,以便在孩子调用它时引用孩子?
【问题讨论】:
-
这里的问题是对 SELF::$TABLE_NAME 的引用。你可以这样在父方法中调用'self'并期望它在子调用方法时引用子表名吗?
标签: php class inheritance methods parent-child