When would you use the $this keyword in PHP?

The most common use case is within Object Oriented Programming, while defining or working within a class. For example:

class Horse {
    var $running = false;

    function run() {
        $this->running = true;
    }
}

As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.


A class may contain its own constants, variables (called "properties"), and functions (called "methods").

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

Some examples of the $this pseudo-variable:

<?php
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);
            echo ")\n";
        } else {
            echo "\$this is not defined.\n";
        }
    }
}

class B
{
    function bar()
    {
        // Note: the next line will issue a warning if E_STRICT is enabled.
        A::foo();
    }
}

$a = new A();
$a->foo();

// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>

The above example will output:

  • $this is defined (A)
  • $this is not defined.
  • $this is defined (B)
  • $this is not defined.

Tags:

Php

Oop