What is Double Colon in PHP? PHP Scope Resolution Operator Explained
Written by Kolade Chris | Aug 3, 2024 | #PHP | 2 minute Read
The double colon (::
) is the scope resolution operator in PHP. It is also known as Paamayim Nekudotayim, which means double colon in Hebrew.
The scope resolution operator is used to access static methods, static properties, and constants of a class without creating an instance of that class. It allows you to access these elements directly from the class itself, rather than from an object instance.
How to Access Static Methods with the Scope Resolution Operator
To use the scope resolution operator to access static methods, attach the double colon to the class name, then call the static method like a regular function:
The example below accesses the numberOfLegs
method from the Animal
class without instantiating it:
If you want to instantiate the class before accessing the numberOfLegs
method, this is how you would have done it:
Join my Free Newsletter
Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies.
No BS. No fluff. Just pure software development goodies on a Sunday every week.
How to Access Static Properties with the Scope Resolution Operator
Accessing static properties with the scope resolution is done the same way you access static methods with it.
That means you need to attach the double colon to the class name, and then the property name. The only thing you need to do differently is to attach the dollar sign to the property name:
In the example below, I accessed the $numberOfLegs
static property without instantiating the Animal2
class:
How to Access Constants with the Scope Resolution Operator
To access constants from a class with the scope resolution operator, you do it like below:
Here’s an example:
Wrapping Up
The scope resolution operator (::
) does not just allow access to static properties, static methods, and constants within a class without the need to instantiate the class. It provides a convenient way to interact with class-level elements directly, simplifying code and improving efficiency in the process.