Current Location: Home> Latest Articles> Detailed Explanation of the self Keyword in PHP: Usage, Examples, and Best Practices

Detailed Explanation of the self Keyword in PHP: Usage, Examples, and Best Practices

gitbox 2025-06-25

1. Introduction to the self Keyword

In PHP, the self keyword is used to access the static members or static methods of a class. When using self, it refers to the current class. In other words, when self is used in the class definition, it represents that class itself; when used inside a method, it refers to the class of that method.

Using the self keyword in a persistent memory web server helps PHP handle your program more efficiently because PHP doesn't need to keep searching for static members or methods in the base class. By using self, PHP knows exactly that the method or property belongs to the current class.

Typically, static members or methods are added to a class to be independent of any object, meaning these methods are called at the class level rather than for each object instance.

2. How to Use the self Keyword

The self:: keyword is used in two primary cases in PHP:

2.1 Using self in Static Methods

In static methods, the self keyword is used to call static methods or static properties:


class Example {
    private static $name = "Cindy";

    public static function sayHello() {
        echo "Hello " . self::$name . "!";
    }
}
Example::sayHello();
        

The above code defines a static class Example and a static method sayHello. In the method, we use self::$name to access the current class's private static property $name. The final output will be:


Hello Cindy!
        

2.2 Using self in Non-Static Methods

In non-static methods, the self keyword is used to represent the current class. In the following example, we define a non-static method called getName() that uses self:: to get the class name:


class Example {
    public function getName() {
        return self::class;
    }
}
$example = new Example();
echo $example->getName();
        

This program will output:


Example
        

3. Summary

The self keyword in PHP is used to access static members and methods, and to represent the current class. It is a very important keyword in PHP development, especially when working with static methods. Mastering the self keyword helps to improve program efficiency and readability while maintaining clean and optimized code.