I have 2 class in my CMS and there are crud functions in "User Class". How can I use database class in another class. I know they both work. But I was previously transferring with the "extends" method. But every time I created an object, the database connection was duplicated. So "extends" was fault for me. I don't want to fault again.
So which is best solution? Do any of these solutions duplicate the database connection?
databaseclass.php:
class database
{
public $connect;
function __construct() {
$this->connect();
}
public function connect() {
$this->connect = new PDO('mysql:host=' . SERVER . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
}
}
userclass.php:
class user
{
function getUser() {
# select an user codes
}
}
Solution - Injection database class
class user { function getUser($database) { $mysql_command = $database->connection->prepare('SELECT * FROM users WHERE id = 1'); $mysql_command->execute(); return $mysql_command->fetch(PDO::FETCH_ASSOC); } }
Solution - Global database class (I want that but everybody suggest first solution) (I want because this solution does not require me to inject each time I create a user object) userclass.php:
class user { function getUser() { global $database; $mysql_command = $database->connection->prepare('SELECT * FROM users WHERE id = 1'); $mysql_command->execute(); return $mysql_command->fetch(PDO::FETCH_ASSOC); } }