尝试使用php oops概念获取非对象的属性

时间:2018-01-05 07:50:20

标签: php oop

我正在尝试使用OO-PHP从数据库中检索数据 这是我的代码

user.php的

 <?php

   require_once("init.php");

   class User{

public $id;
public $username;
public $password;
public $first_name;
public $last_name;


public static function find_all_users(){
    return self::find_this_query("SELECT * FROM users");
}


 public static function find_user_by_id($user_id){
    global $database;
   /* $result_set = $database->query("SELECT * FROM users WHERE id=$user_id LIMIT 1");*/
    $result_set = self::find_this_query("SELECT * FROM users WHERE id=$user_id LIMIT 1");
    $found_user = mysqli_fetch_array($result_set);
    return $found_user;
}


public static function find_this_query($sql){
    global $database;
    $result_set = $database->query($sql);
    $the_object_array = array();
    while($row = mysqli_fetch_array($result_set)){
        $the_object_array[] = self::instantation($row);
    }
    return $result_set;

}


public static function instantation($the_record){
    $the_object = new self;

  /*  $the_object->id         = $found_user['id'];
    $the_object->username   = $found_user['username'];
    $the_object->password   = $found_user['password'];
    $the_object->first_name = $found_user['first_name'];
    $the_object->last_name  = $found_user['last_name'];*/
    foreach($the_record as $the_attribute => $value){
        if($the_object->has_the_attribute($the_attribute)){
            $the_object->$the_attribute = $value;
        }
    }

    return $the_object;
}



private function has_the_attribute($the_attribute){
    $object_properties = get_object_vars($this);
    return array_key_exists($the_attribute, $object_properties);
   }
 }
?>

database.php中

 public function query($sql){

    /*$result = mysqli_query($this->connection,$sql);*/
    $result = $this->connection->query($sql);
    $this->confirm_query($result);
    return $result;
   }

的index.php

          $users = User::find_all_users();
                         foreach($users as $user){
                              echo $user->username;
                              }

尝试从数据库中检索用户时,我收到错误

  

尝试获取非对象的属性

1 个答案:

答案 0 :(得分:0)

问题是,您没有从此方法返回users数组

public static function find_this_query($sql){
    global $database;
    $result_set = $database->query($sql);
    $the_object_array = array();
    while($row = mysqli_fetch_array($result_set)){
        $the_object_array[] = self::instantation($row);
    }
    return $result_set;

}

而是应该将数组作为

返回
public static function find_this_query($sql){
        global $database;
        $result_set = $database->query($sql);
        $the_object_array = array();
        while($row = mysqli_fetch_array($result_set)){
            $the_object_array[] = self::instantation($row);
        }
        return $the_object_array;

    }

如果结果为空,请将其检查为

$users = User::find_all_users();


if($users != null){
foreach($users as $user){
    echo $user->username;
  }
}