Class Constructor

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
slaher
Forum Newbie
Posts: 6
Joined: Thu Dec 16, 2004 4:44 pm
Location: Massachusetts, USA
Contact:

Class Constructor

Post 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]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

$this->a;
$this->b;
slaher
Forum Newbie
Posts: 6
Joined: Thu Dec 16, 2004 4:44 pm
Location: Massachusetts, USA
Contact:

Post 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
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post 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 "".)
Post Reply