PHP & OOP: $this variable

This entry is part 5 of 11 in the series PHP & OOP

In this example, the $this variable is a reference to the current object, which is itself, SimpleClass.  The this reference is commonly found in other object-oriented programming languages.

<?php
class SimpleClass
{
    public $greeting = 'Hi There';
 
    public function displayGreeting() {
        echo $this->greeting;
    }
}
 
//create an instance of the class SimpleClass
$simple_object = new SimpleClass();
echo $simple_object->displayGreeting();
 
?>

The $this->greeting is to access its own variable $greeting.

If you access the $greeting variable without the $this reference, the browser will throw an undefined variable greeting error message.

You can try the below code to see the error message.

<?php
class SimpleClass
{
    public $greeting = 'Hi There';
 
    public function displayGreeting() {
        echo $greeting;
    }
}
 
//create an instance of the class SimpleClass
$simple_object = new SimpleClass();
echo $simple_object->displayGreeting();
 
?>

this_error

Series Navigation<< PHP & OOP: Instance of a class
PHP & OOP: Properties of a class >>

Leave a comment

Leave a Reply