D
D
Dmitry Onatsky2016-11-08 19:11:32
PHP
Dmitry Onatsky, 2016-11-08 19:11:32

How to use database class in methods of other classes?

There is a Database class for working with a database. There is also a Session class for working with sessions. The session class contains queries to the database, and the queries themselves are made thanks to the Database class. How to make Database class visible in Session class methods?
I didn't come up with anything other than how to use $GLOBALS in the constructor. Please tell me how to implement this?

$Database = new Database;

$Session = new Session;

And from what I actually use in the constructor of the Session class:
private Database;

public function __construct()
{
$this->Database = isset($GLOBALS['Database']) ? $GLOBALS['Database'] : new Database;
}

It works, but is such a solution acceptable?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Skobkin, 2016-11-08
@skobkin

I'm afraid to even ask why you decided that $GLOBALS is better than passing a parameter to the constructor.
Urgently read the whole www.phptherightway.com
In particular on the topic: www.phptherightway.com/#dependency_injection
Well, you can look at something like this, for example: php-di.org/doc/understanding-di.html

I
Immortal_pony, 2016-11-08
@Immortal_pony

class Session 
{
    private $Database;

    public function __construct(DatabaseInterface $Database)
    {
        $this->Database = $Database;
    }
}



interface DatabaseInterface {}



class Database implements DatabaseInterface {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question