note 18879 deleted from language.oop by vincent

From: Date: Thu, 11 Sep 2003 19:58:48 +0000
Subject: note 18879 deleted from language.oop by vincent
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-56200@lists.php.net to get a copy of this message
Note Submitter: php@priorwebsites.com ---- If your new to PHP classes, beware of the scope of variables. In particular, if a variable is defined as an implicitly static variable for the class as a whole, make sure you use the $this->my_var syntax, not just $my_var. First, using the scope WRONGLY: class my_wrong_class { /* A general class variable */ $db_link; /* A constructor function for the class */ function my_class() { /* this will give the $db_link variable a value */ /* but only as a local variable in this function. */ $db_link = mysql_connect('localhost','root',''); } function do_something() { $query = "SELECT * FROM my_table"; /* Again, the $db_link reference is wrong! Won't work */ $result = mysql_query( $query, $db_link ); } } Now doing the scope CORRECTLY: class my_right_class { /* A general class variable */ $db_link; /* A constructor function for the class */ function my_class() { /* Ah! Correctly references the class variable */ $this->db_link = mysql_connect('localhost','root',''); } function do_something() { $query = "SELECT * FROM my_table"; /* Ah! Correctly uses the class variable */ $result = mysql_query( $query, $this->db_link ); } } If you are a seasonsed PHP programmer you may say nobody would do that. I as a seasoned non-PHP programmer did, couldn't understand why my code didn't work, and fudged it, till now...

« previous php.notes (#56200) next »