When to Use self and $this in PHP
This snippet is dedicated to the the main ways of using self and $this keywords in PHP. Here, you will learn how to use them and their main differences.
This tutorial covers the most common and practical ways to use self and $this in PHP.
Check out the examples below and enrich your PHP arsenal with these simple and useful tricks.
Using self and $this for Non-static and Static Member Variables
Let’s start with the correct usage of self and $this for static and non-static member variables. Here is an example:
using self and $this for static and non-static member variables php
<?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 comparison, here is an incorrect usage of self and $this for static and non-static member variables:
wrong usage of self and $this for static and non-static member variables php
<?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
Here is an example of polymorphism with $this for member functions:
using $this for member functions php
<?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
Here is an example of suppressing polymorphic behavior by using self for member functions:
using self in php
<?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 a pseudo-variable that references the current object. It is primarily used in object-oriented code. $this is used to call non-static methods. Attempting to call a static method with it will result in an error. This means that $this is not available within a static method.
The Difference Between self and $this in PHP
In PHP, self generally refers to class members, not to any specific object instance. This is because static members (functions or variables) belong to the class itself and are shared by all instances. In contrast, $this refers to the member variables and functions of a specific instance. The $ sign is not used with self because it refers to the class construct, not a variable. Conversely, $this includes the $ sign because it is a pseudo-variable.