I have a "main class" that generates a db access. Something like:
class ObjetBd extends Objet
{
protected $bd;
public function __construct()
{
parent::__construct();
$this->bd = new BD();
$this->bd->connect();
}
}
This is "clean" code to me (I've removed the comment for the sake of compactness).
Now my problem is that $this->bd
is generated for each object.
I'm wondering whether static object are generated + initialized once.
I'd like to call connect()
once and use only one connexion, without using direct calls to static method (i.e. keep on using $this->bd
like before)
If it's the case, could you please say if the following code will work flawlessly, and if it should use less ressources:
class ObjetBd extends Objet
{
static private $bd_static;
protected $bd;
public function __construct()
{
parent::__construct();
if (!isset(self::$bd_static)) {
self::$bd_static = new BD();
self::$bd_static->connect();
}
$this->bd = self::$bd_static;
}
}
Yes, you are doing this correct. Ignore the singleton comment, singletons are a good thing to avoid.
Although I do want to make a suggestion:
I'm going to assume BD is some kind of database. The power of OOP is the ability to subclass things, and replace objects without changing behaviour.
So it may be better to just pass your $bd object in the constructor. Just something to keep in mind. This is called 'dependency injection' or 'inversion of control'.