Search code examples
phpmysqlclassoopmedoo

Medoo object inside a php class


I am getting confused on how to use a meddo config class

$database = new Medoo([
    'database_type' => 'mysql',
    'database_name' => 'name',
    'server' => 'localhost',
    'username' => 'your_username',
    'password' => 'your_password',
]);

inside another class

class Blog {
    public function getBlogs(){
       return $database->select('post', "title");
    }
}

Right now i am using globals to work around is their any direct way that I may use.

I don't want to use it like this

<?php
include 'classes/config.php';

class blog{


function A(){
    global $database;
    return $database->select('post', "title");
    }
}


function B(){
    global $database;
    return $database->select('post', "title");
    }
}


function C(){
    global $database;
    return $database->select('post', "title");
    }
}


?>

Solution

  • Try this by passing the $database in __construct() and then assign $database to class private variable

    include 'config.php';
    class blog{
        private $database = null;
    
        function __construct($db)
        {
            $this->database = $db;
        }
    
        function A(){
            $this->database->select('post', "title");
        }
    }
    
    $obj = new blog($database);
    $obj->A();