Asked 7 years ago
6 Mar 2017
Views 937
jessica

jessica posted

what self do in PHP ?

i found in some code


self::varname;

what is use of self:: in PHP ?
andy

andy
answered Apr 24 '23 00:00

The keyword self in PHP is used to refer to the current class. It is commonly used to access static properties or methods of the class.

The purpose of self is to reference the class in which it is used and not any instance of that class. Therefore, it is often used to access static properties and methods which belong to the class itself, and not to any specific instance of the class.

Here is an example that demonstrates the use of self to access a static property in PHP:



class MyClass {
    public static $myStaticProperty = "Hello, world!";
    
    public static function myStaticMethod() {
        echo self::$myStaticProperty;
    }
}

MyClass::myStaticMethod(); // Output: Hello, world!

In this example, self refers to the MyClass class, and the static property $ myStaticProperty is accessed using self ::$ myStaticProperty .
Post Answer