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?
To access the members of a class from other class. First of all, import the class. Create an object of that class. Using this object access, the members of that class.
Follow the class name with the member-access operator ( . ) and then the member name. You should always access a Shared member of the object directly through the class name. If you have already created an object from the class, you can alternatively access a Shared member through the object's variable.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With