Passing a connection string to your classes has lots of disadvantages and no benefits. You are on the right track, but you want to pass the database object instead of a connection string.
Dependency Injection is a good way of giving your classes access to the database, which simply means to pass dependencies (ie database object) to the objects that need them, rather than the object itself obtaining the dependency from a global variable of some kind.
I would suggest that you use a method like setDb()
on your classes to pass the database objects, and then store it as a property for any internal use.
For example, assuming you have created the database object $db
in an initialisation script:
class SomeClass
{
protected $db;
public function setDb($db)
{
$this->db = $db;
}
public function something()
{
// do some query on the database using $this->db
}
}
$obj = new SomeClass();
$obj->setDb($db);
$obj->something();
DI gives you the benefits that you mentioned: the ability to easily switch the db without having to do lots of work in your methods. There are other benefits, namely ease of testing.