Re: referencing an existing object
| From: | Justin Patrin | Date: | Tue, 15 Jun 2004 18:34:52 +0000 |
| Subject: | Re: referencing an existing object | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-188341@lists.php.net to get a copy of this message | ||
Torsten Roehr wrote:
"Justin Patrin" <papercrane@reversefold.com> wrote in message news:20040615162341.20005.qmail@pb1.pair.com...Global vars are generally a bad idea... It leads to spaghetti code and can end up giving you huge headaches if you're not very careful. Also, I am not saying that $db should be passed into every method. It should be passed into the constructor and assigned as a class variable (as my code above shows). Then, any method in the object can get to it.Bernie wrote:this?Howdy, I am writing a program that has a handful of classes. I would like to be able to get information from one object to the other. I have a couple of my classes extending others, but are there other ways to doGood point Justin. You do not necessarily need a $db var in your data class - just use the passed $db object in your method: class myotherclass {For example: If I have a database class and a separate class that would like to execute an sql statement... class mydbclass { var $db; function mydbclass ($server,$username,$password,$database){I would suggest something like this: class myotherclass {$this->db=mysql_connect($server, $username, $password); mysql_select_db("$database",$db);} function dosql($sql){$result = mysql_query($SQL,$db);} } class myotherclass { function myotherclass(){$sql="select * from mytable";#now, how can I use $mydbclass->dosql($sql) to #execute this statement?#I want to be able to build a bunch of html with #the resulting records and it wouldn't make #sence to build all that in my db class} } Thanks!var $dbfunction myotherclass(&$db){ $this->db =& $db;$sql="select * from mytable";$this->db->dosql($sql); }} $db = new mydbclass(); $other = new myotherclass($db); I would also suggest capitalizing the class names and using another DB abstraction layer (such as PEAR DB or MDB) but that's your option. ;-)var $db;function myotherclass(&$db) {$sql = 'select * from mytable'; $db->dosql($sql); }} Another way is to declare the $db variable global in your methods so that it is available without the need to pass it to *every* single method:
class myotherclass {-- paperCrane <Justin Patrin>function myotherclass() {global $db;$sql="select * from mytable"; $db->dosql($sql); }} But this is a case of personal preference. Best regards, Torsten Roehr