<?php
require_once 'database.php';
class User {
public $id;
public $username;
public $first_name;
public $last_name;
public $password;
public static function find_by_id($id){
$result_array = self::find_by_sql("SELECT * FROM users WHERE id = {$id} LIMIT 1");
return !(empty($result_array))? array_shift($result_array): false;
}
public static function find_by_sql($sql){
global $database;
$result = $database->query($sql);
$object = array();
while ($row = $database->fetct_array($result)){
$object[] = self::instantiate($row);
}
return $object;
}
public static function instantiate($record)
{
$object = new self;
foreach($record as $attribute => $value)
{
if ($object->has_attribute($attribute)){
$object->$attribute = $value;
}
}
return $object;
}
private static function has_attribute($attribute){
$object_var = get_object_vars($this);
return array_key_exists($attribute, $object_var);
}
}
?>
尝试调用函数 has_attribute 时出错。注意:未定义的变量:这个
为什么我不能在私人函数has_attribute($attribute)
get_object_vars
使用它.谁能帮我?谢谢。
$this
不是在静态方法中定义的(它们一般属于类,而不是特定对象) - 但类中的所有方法都定义为 static
.
您可能想更改has_attribute
方法,以便它将User
实例作为参数,但我认为这不是好的设计。事实上,我根本不明白你为什么需要这个方法:对于访问对象的不存在属性的所有情况,都会自动调用所谓的魔术方法 __get():
与属互时调用重载方法 或尚未声明或在 当前范围。[...]
__get()
用于从无法访问的属性中读取数据。
如果定义了has_attribute
以防止访问不存在的属性(例如,记录这些尝试),请将代码移动到 __get
中。
这是因为$this
关键字在静态上下文中不可访问。
Source