Is this a legacy project? If not, I would personally use PDO and namespacing/autoloading. If its a Laravel project, why not use Laravel's DB or Eloquent?
Mar 29, 2017
3
Level 4
PHP OOP- inject DB class to a construct method of another class
I have a Database class for connecting to DB.
<?php
require_once('config.php');
class Database {
function __construct(){
$this->connect();
}
public function connect(){
$this->connection = mysqli_connect(SERVER, USERNAME, PASSWORD, DATABASE);
}
}
?>
And a main class where I need to use the DB connection:
include 'includes/database.php';
class Main{
var $mysqli;
public function __construct(){
$this->mysqli = new Database();
}
But this is not working, since I get an error for queries that are still in the main classes, I intend to move them to the DB class later. But now I am getting an error:
Fatal error: Uncaught Error: Call to undefined method Database::query() in /home/vagrant/Projects/MyProject/index.php on line 262
Queries are done in the Main class:
$result = $this->mysqli->query( "SELECT shops.*, shops.id AS shop,SUM(price)...
And in the index.php file I am instantiating a class like this:
$main = new Main();
Please or to participate in this conversation.