Best way to share a database between classes

I would like to be able to hide my database connection from print_r, so I use a static variable. I have a base class and several classes of objects. Ideally, they will all use the same database connection. What is the best way to share this? The way I configured it now "works," but it just doesn't feel good. There must be a better way to do this. (logically classes should not inherit each other)

class base { private static $db; function __construct() { self::$db = new DB(); // our database class $foo = new Foo( self::$db ); // some other class that needs the same connection } } class Foo { private static $db; function __construct( $db ) { self::$db = $db; } } 
+4
source share
1 answer

you may have a static method in your database class that will return the instance itself.

 $db = DB::getInstance(); 

In addition, you can implement a singleton pattern. You can read about it here.

PHP Templates

The main idea is that you save the database object in a static property, and then in getInstance check whether you set it to return or created a new one, the constructor must be closed so that the object cannot be created anywhere except getInstance .. this guarantees that there is always one instance of a DB object.

+7
source

Source: https://habr.com/ru/post/1347256/


All Articles