note 18879 added to language.oop

From: Date: Fri, 08 Feb 2002 08:25:18 +0000
Subject: note 18879 added to language.oop
Groups: php.notes 
Request: Send a blank email to php-notes+get-26375@lists.php.net to get a copy of this message
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... -- http://www.php.net/manual/en/language.oop.php http://master.php.net/manage/user-notes.php?action=edit+18879 http://master.php.net/manage/user-notes.php?action=delete+18879 http://master.php.net/manage/user-notes.php?action=reject+18879

« previous php.notes (#26375) next »