The self keyword and $this variable are used for two different purposes in PHP object-oriented programming. These are mainly used khổng lồ 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 khổng lồ represent the current object & non-static members of the class. The features and the uses of self keywords & $this variable in PHP class are explained in this tutorial.
Features:The features of this từ khóa 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.
Example 1: Use of the self keyword và call the static function using object
The following example shows the use of the self từ khóa 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 và 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 từ khoá is used in the script khổng lồ read và increment the value of the static variable.
class Visitor //Define a static thành viên private static $counter = 1; //Define Constructor to the value of the static thành viên function __construct() echo "The initial value is: ".self::$counter.""; /*Define a function to lớn increment the value of the static thành viên and return the value lớn 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 đầu ra 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 lượt thích 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,