Hacking with PHP is being updated for PHP 7: pre-order for only $10! >>

The 'this' variable

Once inside an object's function, you have complete access to its variables, but to set them you need to be more specific than just using the variable name you want to work with. To properly specify you want to work with a local variable, you need to use the special $this variable, which PHP always sets to point to the object you are currently working with.

For example:

function bark() {
    print "{$this->Name} says Woof!\n";

Whenever you are inside a function of an object, PHP automatically sets the $this variable contains that object - you do not need to do anything to have access to it.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Objects within objects >>

Previous chapter: Variables

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.