CodeBlanks Logo Icon CodeBlanks

In-class access with $this

PHP course · Intermediate · Lesson 4/115

Learn to access the class's properties and methods with the $this pseudo-variable.

What is $this?

$this is a special variable (pseudo-variable) that refers to the current instance inside a method. When a method is called on an instance, $this represents that instance.

To access a property from inside a method you write $this->name. Here -> is the object access operator. The $ sign is used only before $this; it is not written before the property name.

Accessing methods and properties with $this

With $this you can access not only properties but also other methods of the class. A method call is written $this->greet().

Example: in a Greeter class, the greet method reaches the $name property via $this->name and prints a greeting. Without $this, writing just $name makes PHP look for a local variable and miss the property.

Exercise Write the Greeter class with $this

Define a class named Greeter. Add the property public $name = "Guest";. Write a method greet; in the body write echo "Hello, " . $this->name . "!\n";. Do not call the method. After the class, write echo "Greeter ready" . "\n";.

Show example solution
Inside class Greeter { } add the property, then function greet() { echo ... $this->name ...; }, then echo after the class.
Example solution:
<?php
// Write the Greeter class, the $name property and the greet method
class Greeter {
    public $name = "Guest";
    function greet() {
        echo "Hello, " . $this->name . "!\n";
    }
}
echo "Greeter ready" . "\n";

Test yourself

  1. Which is true about $this?

    • $this represents all instances of a class.
    • $this gives the name of the class.
    • $this refers to the parent class.
    • $this refers to the current instance.
    Show answer

    $this refers to the current instance. — Correct. $this refers to the current instance, giving access to properties and methods.

  2. Complete the property access with $this

    class Greeter {
        public $name = "Guest";
        function greet() {
            echo "Hello, " . ____->name . "!";
        }
    }
    Show answer
    class Greeter {
        public $name = "Guest";
        function greet() {
            echo "Hello, " . $this->name . "!";
        }
    }
  3. Match the $this usage

    $this
    Reference to instance
    ->
    Access operator
    $this->name
    Property access
    $this->greet()
    Method call

All lessons in Intermediate