classfile.php ============== class myclass { public myvar1; public myvar2; function __construct() { if ($his->myvar1 == "a") { $this->myvar2 = "A"; } else { $this->myvar2 = "B"; } } function show_var() { return $this->myvar2; } } Code (markup): index.php =========== include("classfile.php"); $mytest = new myclass(); $mytest->myvar1 = "a"; echo $mytest->myvar1; // Result a echo $mytest->myvar2; // [COLOR="red"]Result B[/COLOR] Code (markup): Question ========= Why Im getting a result of "B" for $this->myvar2? I should get A since Ive modified the value of myvar1 to "a" in my index.php file and based on the condition if myvar1 = "a" myvar2 should return a value of "A".
The code you have posted has 3 parsing errors: line public myvar1; should have been: public $myvar1; line public myvar2; should have been: public $myvar2; line if ($his->myvar1 == "a") should have been if ($this->myvar1 == "a") after correcting the code it does what you say it does. That's because the constructor is only called once when the object $mytest is created (in this line: $mytest = new myclass(); ) Your script modifies the value of myvar2 afterwords but this does not affect myvar2 in any way.
So how can I modify the value of myvar1 to "a" from my index.php so that myvar2 will give me a value of "A".
<?php class myclass { public $myvar1; public $myvar2; function __construct($init_val) { $this->myvar1=$init_val; if ($this->myvar1 == "a") $this->myvar2 = "A"; else $this->myvar2 = "B"; } function show_var() { return $this->myvar2; } } $mytest = new myclass("a"); echo $mytest->myvar1; // Result a echo $mytest->myvar2; // Result A ?> PHP:
meaning if I need to change / pass multiple variables Ill do it this way function __construct($init_val1, $init_val2, $init_val3) ... $mytest = new myclass("a", "b", "c"); Code (markup): Cant I not do it something like this $init_val1 = "a" $init_val1 = "b" $init_val1 = "c" Code (markup):
because you are calling function show_var() { return $this->myvar2; } thats why you are getting this value.