pseudo-variable $this?

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
MertTheGreat
Forum Newbie
Posts: 1
Joined: Wed Jul 01, 2009 2:02 pm

pseudo-variable $this?

Post 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.
BornForCode
Forum Contributor
Posts: 147
Joined: Mon Feb 11, 2008 1:56 am

Re: pseudo-variable $this?

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: pseudo-variable $this?

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply