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.
Đang xem: The difference between self::, static:: and parent:: in php
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.
Xem thêm: Bí Quyết Hàn Gắn Hôn Nhân Sau Ngoại Tình, Cách Hàn Gắn Hôn Nhân Sau Ngoại Tình
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.””; } /*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 functionecho $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.
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.
Linux Hint LLC,