php

Use of self or $this in PHP

The self keyword and $this variable are used for two different purposes in PHP object-oriented programming. These are mainly used to represent the class members of a particular class. The self keyword is used to represent the current and static members of the class. The $this variable is used to represent the current object and non-static members of the class. The features and the uses of self keywords and $this variable in PHP class are explained in this tutorial.

self keyword:

Features:
The features of this keyword are mentioned below:

  • No special symbol is required to use this keyword.
  • It is used with the scope resolution operator (::) of PHP.
  • It does not refer to any instance of the class.
  • It represents the static members of the class that are used by all class instances.
  • It does not require to initiate an object.

Syntax:
self::$static_member

Example 1: Use of the self keyword and call the static function using object

The following example shows the use of the self keyword to access the static members of any class. Create a PHP file with the following code that contains a class named “Visitor”, with a static variable and function. When any object of this class creates, then the initial value of the static variable will be printed. The increment_counter() function will increment the value of the static variable by 1. The self keyword is used in the script to read and increment the value of the static variable.

<?php
class Visitor {
    //Define a static member
    private static $counter = 1;
    //Define Constructor to the value of the static member
    function __construct() {
       echo "The initial value is: ".self::$counter."<br />";
    }

    /*Define a function to increment the value of the static member
    and return the value to the caller*/


    public static function increment_counter() {
        self::$counter++;
        return "The current value is: ".self::$counter;

    }
}

//Create object of the class
$object = new Visitor();
//Call the static function
echo $object->increment_counter()."
"
;
?>

Output:
The following output will appear after running the script. The initial value of $counter is 1, which becomes 2 after the increment.

Example-2: Use of the self keyword and call the static function directly

In the following example, the Book class contains three static variables and when the object of this class is created, then these variables will be initialized with three values by using the self keyword. When the addBook() method will call using object then the static method, display(), will call by using the self keyword.

How the static members of the class can be accessed without creating any object is also shown in this tutorial.

<?php

class Book
{
    //Declare a static members
    public static $id;
    public static $bookname;
    public static $stock_qty;

    //Declare constructor
    public function __construct($id,$bookname,$stock_qyt)
    {
        self::$id = $id;
        self::$bookname = $bookname;
        self::$stock_qty = $stock_qty;
    }

    //Declare regular method
    public function addBook($qty)
    {
        self::$stock_qty += $qty;
        self::display();
    }

    //Declare static method
    public static function display()
    {
        echo "Book id: ".self::$id."<br />";
        echo "Book name: ".self::$bookname."<br />";
        echo "Current stock: ".self::$stock_qty."<br />";
    }

}

//Initialize the static variables using constructor
$bookObject = new Book('123','Learning PHP',120);

//Call static method using self keyword
$bookObject->addBook(30);

echo "------------------------------<br />";

//Call static method directly
Book::display();

?>

Output:
The following output will appear after running the script. The display() method is called two times here. It is called by using the self keyword and directly with the class name.

$this variable:

$this variable is mainly used in object-oriented programming to set a reference to the current object of the class. It is used to refer to the non-static member and function of the class only otherwise it will generate an error. The uses of this variable are shown in the next part of this tutorial.

Example-3: Use of the $this variable to access the private class member

In the following example, the Customer class is created with two private members, a constructor and a method. Private members of the class are accessible inside the class only. The $this variable is used here to set and get the values of the private members. When the object of the class is created, then the members of the class will be initialized inside the constructor. When the fullName() method will be called, then the values of the private members will be printed using the $this variable.

<?php
class Customer {
    //Declare private member
    private $firstname;
    private $lastname;

    //Declare instructor
    public function __construct($fn, $ln)
    {
        $this->firstname = $fn;
        $this->lastname = $ln;
    }
    //Print the fullname of the customer
    public function fullName() {
        echo "The customer name is: ".$this->firstname." ".$this->lastname;
    }
}
//Create object
$customer = new Customer('Mohammed','Rafiq');
//Call public function fullName()
$customer->fullName();

?>

Output:
The following output will appear after running the script.

Example-4: Use of both the self keyword and $this variable

The following example shows the use of both the self keyword and $this variable. The employee class contains a static and private member. The self keyword is used to access the static member, and the $this variable is used to access the non-static member in the script.

<?php
class Employee {
    //Declare a static member
    public static $name;
    //Declare a private member
    private $salary;
    //Declare the constructor
    public function __construct($name, $salary)
    {
        self::$name = $name;
        $this->salary = $salary;
    }
    //Print the fullname of the customer
    public function details() {
        echo "Employee name: ".self::$name."<br />";
        echo "Salary: ".$this->salary;
    }
}
//Create object
$emp = new Employee('Mir Sabbir',500000);
//Call public function fullName()
$emp->details();

?>

Output:
The following output will appear after running the script. Here, the employee’s name is printed using the self keyword, and the salary is printed using the $this variable.

Video Tutorial

Conclusion:

The self keyword and $this variable are used for different purposes inside the class. Both are used to access the members of the class. The uses of the self keyword and $this variables are shown by using four different examples in this tutorial, to help the reader know the use of the self keyword and $this variable, as well as apply them properly in their PHP script.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.