When to Use self and $this in PHP

In the given tutorial, we have chosen the most common and handy ways of using self and $this in PHP.

Check out the examples below and enrich your PHP arsenal with these simple and useful tricks.

Watch a course Learn object oriented PHP

Using self and $this for Non-static and Static Member Variables

Let’s start at representation of the correct usage of self and $this for static and non-static member variables. Here is an example:

<?php

class X
{
  private $non_static_member = 1;
  private static $static_member = 2;

  function __construct()
  {
    echo $this->non_static_member . ' ' . self::$static_member;
  }
}
new X();

?>

For the comparison, we demonstrate a wrong method of using self and $this for static and non-static member variables below:

<?php 

class X
{
  private $non_static_member = 1;
  private static $static_member = 2;
  function __construct()
  {
    echo self::$non_static_member . ' ' . $this->static_member;
  }
}
new X(); ?>

Polymorphism with $this

An example of polymorphism with $this for member functions will look as follows:

<?php 

class X
{
    function foo()
    {
        echo 'X::foo()';
    }
    function bar()
    {
        $this->foo();
    }
}
class Y extends X
{
    function foo()
    {
        echo 'Y::foo()';
    }
}
$x = new Y();
$x->bar();

?>

Suppressing Polymorphic Behavior with self

An example of suppressing polymorphic behavior by applying self for member function is demonstrated below:

<?php
class X
{
  function foo()
  {
    echo 'X::foo()';
  }
  function bar()
  {
    self::foo();
  }
}
class Y extends X
{
  function foo()
  {
    echo 'Y::foo()';
  }
}
$x = new Y();
$x->bar(); ?>

About $this in PHP

In PHP, $this is considered a pseudo-variable that is a reference to the current object. Most of the time, it is implemented in object-oriented codes. The variable $this is used for calling non-static methods. In case one is attempting to call a static method, then an error will occur. It means that the variable $this is now available within a static method.

The Difference Between self and $this in PHP

In PHP, the self, generally, belongs to the class members, but never for any exact object. The reason is that the static members (functions or variables) are class members that are shared by all the objects of the class. Whereas, $this refers to the member variables and function for a particular instance. The $ sign is not used for self as it doesn’t connote a variable, but the class construct. As $this doesn’t reference a particular variable, it includes a $ sign.