Page 1 of 1

pseudo-variable $this?

Posted: Wed Jul 01, 2009 2:07 pm
by MertTheGreat
pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.


hi,

can somebody guide me find information about this variable.

it is said that this variable is used when a method is called from within an object context, as it said in manual. But why, why can't we call like that

Code: Select all

<?php
 
class This {
  private $a=1;
  
  public function get_a() {
    //return $this->a;
    return $a;
  }
 
  
}
?>
I know this variable called pseudo-variable, I am not a programmer I hope guys can tell me why we have to use $this variable.


pickle | Please use [ code=php ], [ code=text ], etc tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: Posting Code in the Forums to learn how to do it too.

Re: pseudo-variable $this?

Posted: Wed Jul 01, 2009 2:40 pm
by BornForCode
Because $a is not a class member is a variable inside your function which is not initialized with a value.
In ca class matter $this->a will target to a class member, and $a is local.

Re: pseudo-variable $this?

Posted: Thu Jul 02, 2009 10:08 am
by pickle
$this refers to the current object:

Code: Select all

class Car
{
  private $colour = 'red';
  private $year = '1979';
 
  function getColour()
  {
    return $this->colour;
  }
}
 
 
$MyCar = new Car();
echo $MyCar->getColour();
The output of this would be "red".

Your code would work if you uncommented that line, and added some code that instantiates your class & calls get_a(). Naming your class "This" however, might cause some issues.