Pages

Sunday, September 19, 2010

Using $this


Inside a class, $this is a special variable that refers to the properties of the same class. $this can’t be used outside of a class. It’s designed to be used in statements inside a class to access variables inside the same class.

The format for using $this is the following:

 $this-> variable name;

For example, in a Car class that has an attribute $gas, we would access $gas in the following way:

$this->gas;

Using $this refers to $gas inside the class. We can use $this in any of the following statements as shown:

$this->gas = 20;

if($this->gas > 10)

$product[$this->size] = $price;

As we can see, we use $this-> variable name in all the same ways we would use $varname.

Notice that a dollar sign ($) appears before this but not before gas. Don’t use a dollar sign before gas — as in    $this->$gas — because it changes statement’s meaning. We may or may not get an error message, but it isn’t referring to the variable $gas inside the current class.

No comments:

Post a Comment