문제

I am trying to learn how to use LSB. I am trying to separate my common db methods into class DatabaseObject and extend it to all classes that will be using them. Common db methods being find_by_id(), create(), delete(), etc.

$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
도움이 되었습니까?

해결책

Works fine for me. The error sounds like you have a DatabaseObject instance instead of a Personnel instance.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top