I have a class like this:
class sqlClass {
var $myvar = "test value 1"
public function test01() {
global $myvar;
//some operations here
$myvar = "test value 2"
return true;
}
}
In other file I have this PHP script:
include_once('functions.php'); // where my class is
$data = new sqlClass();
if ($data->test01()) {
echo $data->myvar;
} else { echo "No value"; }
Well in this example test01() is always true, so I have a guarantee that $myvar changes, BUT, when I print $myvar after I executed the function in the class that is supposed to change the value of it, it prints the old value “test value 1” instead of “test value 2”. So, what am I missing?
Ok so first of all you shouldnt use the
varkeyword. Thats php4 which you shouldnt be using unless you are maintaining a legacy app. Instead you use one of the visibility keywords –public,protected, orprivate.Secondly you shouldnt use
globalwithin a class there shouldnt be a need. to access a class member you use$this->memberNameif you need access to variables outside the class you should pass those in as arguments to your methods or constructor.So given all that this is what your code should look like:
Having said that i would read the entire section on OOP in the manual for php5