我正在尝试学习如何使用 LSB 。 我正在尝试将我常用的 db 方法分解为 < code> 类数据库Object , 并将其推广到所有使用这些方法的类别。 普通 db 方法为 < code> find_ by_ id () code >, < code > create () , < code> delete () , < code > < () etete () 等。
$username = trim($_POST[ username ]);
$password = trim($_POST[ password ]);
$found_personnel = Personnel::authenticate($username, $password);
Classes
class DatabaseObject {
public static function find_by_sql($sql="") {
global $database;
$result_set = $database->query($sql);
$object_array = array();
while ($row = $database->fetch_array($result_set)) {
$object_array[] = self::instantiate($row);
}
return $object_array;
}
private static function instantiate($record) {
$object = new self;
foreach($record as $attribute=>$value){
if ($object->has_attribute($attribute)) {
$object->$attribute = $value;
}
}
return $object;
}
private function has_attribute($attribute) {
$object_vars = $this->attributes();
return array_key_exists($attribute, $object_vars);
}
protected function attributes() {
$attributes = array();
//this static::$db_fields is where my problem is
foreach(static::$db_fields as $field) {
if(property_exists($this, $field)) {
$attributes[$field] = $this->$field;
}
}
return $attributes;
}
}
class Personnel extends DatabaseObject {
protected static $table_name = "personnel";
//this is the property I am trying to access in DatabaseObject
protected static $db_fields = array( id , username , password , first_name , last_name , email , permissions );
public static function authenticate($username="", $password="") {
global $database;
$username = $database->escape_value($username);
$password = $database->escape_value($password);
$sql = "SELECT * FROM " . self::$table_name . " ";
$sql .= "WHERE username = {$username} ";
$sql .= "AND password = {$password} ";
$sql .= "LIMIT 1";
$result_array = parent::find_by_sql($sql);
return !empty($result_array) ? array_shift($result_array) : false;
}
}
The error I get:
Fatal error: Access to undeclared static property: DatabaseObject::$db_fields