Jump to content


Photo

Strange problems with PHP4 (OOP)


  • Please log in to reply
5 replies to this topic

#1 olegk

olegk
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 28 August 2006 - 11:40 PM

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

PHP 4.4.2

<?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();

?>

#2 sanfly

sanfly
  • Members
  • PipPipPip
  • Advanced Member
  • 344 posts
  • LocationNew Zealand

Posted 28 August 2006 - 11:49 PM

function testfunc()
  {
      $this->$a="A";
      echo $this->$a;
      $this->$b="B";
      echo $this->$a;
  }


should the line in red be:

echo $this->$b;

If you're not part of the solution, you're part of the precipitate

#3 olegk

olegk
  • New Members
  • Pip
  • Newbie
  • 3 posts

Posted 28 August 2006 - 11:52 PM

...
should the line in red be:
...


No, that's the point. If it were $this->$b, I would expect the code to print "AB", but I print out $this-$a twice, and for some reason the second time it turns into "B"


#4 drkstr

drkstr
  • Members
  • PipPipPip
  • Advanced Member
  • 66 posts
  • LocationSeattle, WA - USA

Posted 29 August 2006 - 01:48 AM

This might be with PHP 5, but I think you need to access your vars with:

      $this->a="A";
      echo $this->a;
      $this->b="B";
      echo $this->a;
regards,
...drkstr

#5 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 29 August 2006 - 08:45 AM

To access your vars that is in the same class/function you need to use $this->youVarNameHere just as drkstr pointed out above. This is the same for PHP4 and PHP5.
You do not put the dollar sign after $this-> you just the name of the variable, ie $this->a

#6 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 29 August 2006 - 11:54 AM

Is there any reason you didn't take this answer from the other forum you posted this on?




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users