I'm new to object oriented PHP, so I'm sure of the good or bad practices. The below code is working perfectly, I just don't know if it is a bad or good approach to use most of the methods as static and declare class properties as public.
Could someone provide me some advise?
In users.php
<?php
class Users{
public $user_id, $user_name, $user_email, $user_fname, $user_lname, $user_role;
public static function display_users(){
$display_users[] = self::find_all_query("SELECT * FROM users");
return (!empty($display_users)) ? array_shift($display_users) : false;
}
public static function find_all_query($sql){
global $database;
$result = $database->query($sql);
$db_result = array();
while($row = mysqli_fetch_assoc($result)){
$db_result[] = self::instantiation($row);
}
return $db_result;
}
public static function instantiation($row){
$the_users_object = new Users();
foreach ($row as $attribute => $data) {
if($the_users_object->has_the_attribute($attribute)){
$the_users_object->$attribute = $data;
}
}
return $the_users_object;
}
private function has_the_attribute($attribute){
$users_properties = get_object_vars($this);
return array_key_exists($attribute , $users_properties);
}
}
?>
In admin-users.php
<?php
$display_users = Users::display_users();
foreach ($display_users as $users) {
echo "<tr>";
echo "<td> $users->user_id </td>";
echo "<td> $users->user_name </td>";
echo "<td> $users->user_email </td>";
echo "<td> $users->user_fname </td>";
echo "<td> $users->user_lname </td>";
echo "<td> $users->user_role </td>";
echo "</tr>";
}
?>
In database.php
<?php
// require_once("init.php");
class Database{
private $connection;
function __construct(){
$this->open_db_connection();
}
public function open_db_connection(){
$this->connection = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
if($this->connection -> connect_error){
die('<h1>Database Connection Failed!!!!</h1>.'. $this->connection -> connect_error);
}
}
private function checkQuery($query){
if(!$query){
die("<h1>Query Failed!!!!</h1> ". $this->connection -> error);
}
}
public function query($sql){
$result = mysqli_query($this->connection , $sql);
$this->checkQuery($result);
return $result;
}
}
$database = new Database();
?>