Page 1 of 1

Major problems with PHP4

Posted: Mon Aug 28, 2006 6:31 pm
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]

Posted: Mon Aug 28, 2006 7:13 pm
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();
?>

Posted: Mon Aug 28, 2006 7:16 pm
by olegkikin
If I'm echoing $this-$a twice, why does it echo "A" the first time and "B" the second time?

Posted: Mon Aug 28, 2006 7:29 pm
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;

Posted: Tue Aug 29, 2006 3:06 am
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".

Posted: Tue Aug 29, 2006 3:28 am
by CoderGoblin
Looks as though you are fooling php and yourself with variable variables...

Php Manual Variable Variables

Regards