Andreas Korthaus wrote:
Hi Gustav!
Gustav Wiberg wrote:
My oponion is that is insane to use global variables. The main
drawback with global variables is that is very easy to mix up
variables, and keep track of what variable belongs to what. So an
advice: Don't use it!
Ok, so what's your recommendation to solve the problem with using a DB
class in many other objects/methodes? Think of a DB class:
class DB {...}
And a lot of classes which want to use the DB class:
class Foo {
function saveChangesInDb() {...}
}
class Bar {
function saveChangesInDb() {...}
}
- You can use a global "$db = new DB..." and pass it to every
class/methode,
- you can make $db "global" in each methode,
- you can create a new instance ("new DB") in every methode (but you
usually only want a single DB-connection per script, and where do you
pass config-data to access the DB?) or
- use a factory/singleton, which is not so much better than a global
variable (and again, what about config-data?).
So what's the way you'd recommend and why?
IMHO, the only way a global variable would have sense is in an
environment where you can be assured there's a "DBClass" $db instance,
and that it would never ever be a $db var that's not a DBClass instance
nor will $db ever be missing. So, can you guarantee this at the present
and to the end of times? :)
I think it would be better to create an instance of $db whatever the
script you need it, and pass it to every class-constructor as a
byref-parameter; i.e.
$db =& new DBClass();
···
$class1 =& new Class1($db);
···
$class2 =& new Class2($db);
Now, if you insist on using global vars, then maybe, just maybe, it
would be better to let that byref-param be optional, and check in the
constructor for a global DBClass instance $db if no DBClass instance was
given, but then again the problem would be pretty much the same. Try
not to rely on global vars, bear in mind that global vars almost always
give too little info and do not reflect themselves on the function
prototype --well, if you have a smart IDE/editor that understand PHPDoc
comments (or something like that) and you do document their existance,
it might not be that bad, but still try to avoid them.
--
Atentamente,
J. Rafael Salazar Magaña
Innox - Innovación Inteligente
Tel: +52 (33) 3615 5348 ext. 205 / 01 800 2-SOFTWARE
http://www.innox.com.mx
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php