Monday, 28 January 2013

Php this keyword

Today i am going to familiarize you guys with the $this keyword in php . So what does $this do ? Essentially it is used to access member variables from inside a member function in a class .

Consider the following example :-

class webdevfunda
{
public $var;
private $_var;
public function foo()
{
$this->var = 2;
$this->_var = 3;
}
}

class phptute extends webdevfunda
{
public function zoo()
{
$this->var =4;
$this->_var=6; //Will produce an error
}
}

Note that when zoo tries to access _var it produces an error . This is because zoo is trying to access a private variable of it's parent class which it does not have access to . So it produces an error . In case of a function we can use the self::function_name(); command to invoke the function .

2 comments: