Possible Duplicate:
PHP: self vs this
Hello,
Could you help me understanding the meaning of the PHP variable name $this
?
Thank you for your help.
Possible Duplicate:
PHP: self vs this
Hello,
Could you help me understanding the meaning of the PHP variable name $this
?
Thank you for your help.
$this
refers to the class you are in.
For example
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
Hope this helps.
You might want to have a look at the answers in In PHP5, what is the difference between using self and $this? When is each appropriate?
Basically, $this
refers to the current object.
$this
is a protected variable that's used within a object, $this
allows you to access a class file internally.
Example
Class Xela
{
var age; //Point 1
public function __construct($age)
{
$this->setAge($age); //setAge is called by $this internally so the private method will be run
}
private function setAge($age)
{
$this->age = $age; //$this->age is the variable set at point 1
}
}
Its basically a variable scope issue, $this
is only allowed within a object that has been initiated and refers to that object and its parents only, you can run private methods and set private variables where as out side the scope you cannot.
also the self
keyword is very similar apart from it refers to static methods within class, static basically means that you cant use $this
as its not an object yet, you must use self::setAge();
and if that setAge
method is declared static then you cannot call it from an instant of that object / object
Some links for you to get started: