PHP Late Static Binding错误

时间:2012-05-26 17:04:14

标签: php oop late-static-binding

我正在尝试学习如何使用LSB。我试图将我的常见db方法分成class DatabaseObject并将其扩展到将使用它们的所有类。常见的数据库方法是find_by_id()create()delete()

$username = trim($_POST['username']);
$password = trim($_POST['password']);

$found_personnel = Personnel::authenticate($username, $password);

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;

}
}

我得到的错误:

Fatal error: Access to undeclared static property: DatabaseObject::$db_fields

1 个答案:

答案 0 :(得分:0)

对我来说很好。该错误听起来像是DatabaseObject实例,而不是Personnel实例。