Scope Resolution Operator ::


The scope resolution operator, also known as the double colon (::), is a token that allows access to static, constant, and overridden properties or methods of a class in PHP.

Here’s a bit more detail on how it’s used:

1. Accessing Static Members

You can use the scope resolution operator to access static methods and properties. Since they belong to the class itself rather than an instance of the class, you don’t need to create an object to access them.

class MyClass {
    public static $myStaticVar = 'I am static';

    public static function sayHello() {
        return 'Hello!';
    }
}

echo MyClass::$myStaticVar; // Outputs 'I am static'
echo MyClass::sayHello();   // Outputs 'Hello!'

2. Accessing Constants

You can define constants within a class, and these can also be accessed using the scope resolution operator.

class MyClass {
    const MY_CONSTANT = 'I am constant';

    public static function showConstant() {
        return self::MY_CONSTANT;
    }
}

echo MyClass::MY_CONSTANT;          // Outputs 'I am constant'
echo MyClass::showConstant();       // Outputs 'I am constant'

3. Late Static Bindings

PHP has a feature called “late static bindings,” which allows you to refer to the called class in the context of static inheritance. The static:: keyword is used for this purpose.

class ParentClass {
    public static function who() {
        return 'ParentClass';
    }

    public static function test() {
        echo static::who(); // Outputs 'ChildClass' when called from a child class
    }
}

class ChildClass extends ParentClass {
    public static function who() {
        return 'ChildClass';
    }
}

ChildClass::test(); // Outputs 'ChildClass'

Summary

The scope resolution operator (::) is a powerful feature in PHP that allows you to access elements that are part of the class itself, like static methods, static properties, and constants. It’s a crucial part of working with object-oriented programming in PHP, and it’s a tool that you’ll likely find yourself using quite a bit as a web developer.