Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a database class, which is used to make select, update, delete MySQL queries.

Now, I want to create a MySQL query inside another class, but if I define $db = new DB(); in index.php, I can't use the $db var in another class. Do I have to define the variable $db over and over again, if I want to make a query? Or is there a way to make the $db var with an object global var?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
373 views
Welcome To Ask or Share your Answers For Others

1 Answer

The cleanest approach would be to aggregate the database class where needed by injecting it. All other approaches, like using the global keyword or using static methods, let alone a Singleton, is introducing tight coupling between your classes and the global scope which makes the application harder to test and maintain. Just do

// index.php
$db  = new DBClass;               // create your DB instance
$foo = new SomeClassUsingDb($db); // inject to using class

and

class SomeClassUsingDb
{
    protected $db;
    public function __construct($db)
    {
        $this->db = $db;
    }
}

Use Constructor Injection if the dependency is required to create a valid state for the instance. If the dependency is optional or needs to be interchangeable at runtime, use Setter Injection, e.g.

class SomeClassUsingDb
{
    protected $db;
    public function setDb($db)
    {
        $this->db = $db;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...