Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access an object from another class?

Tags:

php

class

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?

like image 610
Mike Avatar asked Sep 29 '10 08:09

Mike


People also ask

How do you access an object of one class from another class?

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.

How do you access objects in 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.


1 Answers

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;
    }
}
like image 81
Gordon Avatar answered Sep 20 '22 02:09

Gordon