Leff7's avatar
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();
0 likes
3 replies
zachleigh's avatar

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?

Leff7's avatar
Level 4

Yes, it is a legacy project, and I am planning on moving everything to Laravel, but as of now, before I move it to Laravel,I just wanted to make some kind of flexible way of passing the values to mysqli_connect method, but not sure how to do that?

zachleigh's avatar

The Database class doesn't have a query method.

Please or to participate in this conversation.