【发布时间】:2014-04-17 02:43:15
【问题描述】:
所以我正在关注 Lynda.com 上有关高级 PHP 的教程。他们提到了后期静态绑定,但我猜他们制作教程时 PHP 5.3 还没有推出,所以我试图弄清楚如何在扩展类中使用“创建”函数进行 CRUD,并将属性从被调用的类中提取到功能。我觉得我错过了一些非常简单的东西,它在我的数据库中插入了一个新行,只是没有内容。这是代码,任何建议都会很有用。
test.php 文件中的 PHP 代码...
<?php
$user = new User();
$user->username = "johnsmith";
$user->password = "555";
$user->first_name = "john";
$user->last_name = "smith";
$user->create();
?>
扩展 DatabaseObject 类的用户类...
class User extends DatabaseObject {
protected static $table_name="users";
protected static $db_fields = array('id', 'username', 'password', 'first_name', 'last_name');
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
}
具有后期静态绑定的DatabaseObject 类...
class DatabaseObject {
protected static function attributes() {
$attributes = array();
foreach(static::$db_fields as $field) {
if(property_exists(get_called_class(), $field)) {
$attributes[$field] = get_called_class()->$field;
}
}
return $attributes;
}
protected static function sanitized_attributes() {
global $database;
$clean_attributes = array();
foreach(self::attributes() as $key => $value) {
$clean_attributes[$key] = $database->escape_value($value);
}
return $clean_attributes;
}
public static function create() {
global $database;
$attributes = self::sanitized_attributes();
$sql = "INSERT INTO ".static::$table_name." (";
$sql .= join(",", array_keys($attributes));
$sql .=") VALUES ('";
$sql .= join("', '", array_values($attributes));
$sql .= "')";
if($database->query($sql)) {
static::$id = $database->insert_id();// get last id saved in database and puts it in the id arguement
return true;
} else {
return false;
}
}
【问题讨论】:
-
请参阅:php.net/manual/en/function.get-called-class.php 获取 get_call_class()
标签: php content-management-system dynamic-programming semantic-markup object-oriented-database