jump to navigation

Using the keyword “$this” in PHP October 11, 2010

Posted by Tournas Dimitrios in PHP.

Welcome to another part of the serie ” The basics of OOP with PHP ” follow up …

You may have come across number of functions and variables inside a class and perhaps you don’t even know how they’re called or invoked. These functions and variables that belong to a class are called as properties and methods, or simply members, of this class.In PHP, the keyword “$this”  is used as a self reference of a class and you can use it for calling and using these properties and methods as shown in the example bellow. Create a file ClassOne.php with code bellow:

<? p  h p
class ClassOne
    // this is a property of this class
    public $propertyOne;

    // When the ClassOne is instantiated, the first method called is
    // its constructor, which also is a method of the class
    public function __construct($argumentOne)
        // this key word used here to assign
        // the argument to the class
        $this->propertyOne = $argumentOne;

    // this is a method of the class
    function methodOne()
        //this keyword also used here to use  the value of variable $var1
        return 'Method one print value for its '
             . ' property $propertyOne: ' . $this->propertyOne;

In this class, we are also using the visibility declarations (public), which means whether the members are accessible on a subclass – we will discuss it later – or instance.
Another thing you must be curious about is the use of ‘->’. This is an object pointer and, on PHP, it’s used for accessing members inside an object.

Now, let’s test your class! Create another file, called use.php with the following code:

< ? p h p
// include your class file
require_once 'ClassOne.php';

// Create an instance of your class
$classOneInstance = new ClassOne('Hello');

// And test it
print $classOneInstance->propertyOne . '
print $classOneInstance->methodOne();

– Note that in both files we’re not using the enclosing PHP tags (?>). Once they have only PHP code, it’s not needed and it’s also a good practice to avoid them on pure PHP files.



1. viki - October 16, 2013


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s