Major problems with PHP4

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
olegkikin
Forum Newbie
Posts: 12
Joined: Wed Jun 21, 2006 10:01 pm

Major problems with PHP4

Post by olegkikin »

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


This code prints out "AB", and it should print out "AA". What's wrong with me?

PHP 4.4.2

Code: Select all

<?php
class test
{
  var $a="";
  var $b="";
   function testfunc()
   {
      $this->$a="A";
      echo $this->$a;
      $this->$b="B";
      echo $this->$a;
   }
}

$t=new test;
$t->testfunc();

?>

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

You are echoing out $this->a twice. Although the more I think about it, your class might do better like this...

Code: Select all

<?php
class test
{
  var $a = '';
  var $b = '';

  function testfunc()
  {
    $this->a = 'A';
    $this->b = 'B';

    echo $this->a;
    echo $this->b;
  }
}

$t = new test;
$t->testfunc();
?>
olegkikin
Forum Newbie
Posts: 12
Joined: Wed Jun 21, 2006 10:01 pm

Post by olegkikin »

If I'm echoing $this-$a twice, why does it echo "A" the first time and "B" the second time?
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

It might have something to do with the dollarsign notation you are using for the class var.

Code: Select all

$this->$var;
is not the same as

Code: Select all

$this->var;
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

Code: Select all

$this->$a="A"; //Sets ${no name set} to A
      echo $this->$a;
      $this->$b="B"; //Sets ${no name set} to B
      echo $this->$a;
If $a and $b had values then the code would be fine .. at the moment they're both set to the same thing, so "A" is overwritten with "B".
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Looks as though you are fooling php and yourself with variable variables...

Php Manual Variable Variables

Regards
Post Reply