Page 1 of 1

Class Constructor

Posted: Tue Jan 04, 2005 5:32 pm
by slaher
Hi


The expected output from the following code is 1,2
The actual output I am getting is 2,2

Your help would be appreciated.

Thanks,
-sl

Code: Select all

class test {
        var $a;
        var $b;
        
        function test() {
                 $this->setA(1);
                 $this->setB(2);
        }
        
        function getA() { return $this->$a; }
        function setA($p_a) { $this->$a = $p_a; }

        function getB() { return $this->$b; }
        function setB($p_b) { $this->$b = $p_b; }
  }
  
  $testobj = new test();
  echo $testobj->getA().",".$testobj->getB();

feyd | Help us, help you. Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read: :arrow: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Tue Jan 04, 2005 5:39 pm
by feyd

Code: Select all

$this->a;
$this->b;

Posted: Tue Jan 04, 2005 5:46 pm
by slaher
Many thanks.
Sorry for not following the convention; I didn't realize I needed to use

Code: Select all

rather than

Code: Select all

. Will make a point of it in future!
Thanks again.

-sl

Posted: Tue Jan 04, 2005 6:02 pm
by onion2k
For future reference, and its completely optional, you could always do this:

Code: Select all

function getsetA($p_a="") {
  if ($p_a!=="") {
    $this->a = $p_a;
  }
  return $this->a;
}
If getsetA() is called without a parameter it just returned $this->a, if a parameter is passed it sets $this->a to it and returns $this->a. In my opinion its neater than having 2 seperate methods. (Though it does stop you ever setting $this-> to equal "".)