How to Use the Scope Resolution Operator in PHP
In this snippet, you will find comprehensive information about the scope resolution. Explore the ways of using the scope resolution operator in PHP.
The scope resolution operator (also known as the double colon) is a token that helps to reach the static, constant, and overridden properties of a class.
You can use it for referring to properties, methods, and constants in classes and objects.
It is typically used with a class name, object instance, or keyword.
Below, you can find several examples of using the scope resolution operator.
Defining Constants Inside a Class
In this example, we demonstrate how to define constants within a class:
php define constants in a class
<?php
class democlass
{
const PI = 3.14;
}
echo democlass::PI;
?>The output is the following:
3.14Accessing Properties or Methods Inside Class Definition
There exist three special keywords (parent, self, and static) that are used for accessing properties or methods inside the class definition.
php access properties or methods inside class definition
<?php
// Declare parent class
class demo
{
public static $bar = 10;
public static function func()
{
echo static::$bar . "\n";
}
}
// Declare child class
class Child extends demo
{
public static $bar = 20;
}
// Call for demo's version of func()
demo::func();
// Call for child's version of func()
Child::func();
?>The output will be:
10
20Note that self:: refers to the class where the method is defined, while static:: uses late static binding to refer to the class that actually called the method.
Calling the Parent Version of the Method
In case an extending class overrides the function of its parent, the compiler runs the child class’s version of the method. Yet, the child class has to call its parent’s version of the method.
Here is how it looks like:
php class child extends demo
<?php
class demo
{
public function myfunc()
{
echo "myfunc() of parent class\n ";
}
}
class child extends demo
{
public function myfunc()
{
// Call parent's version
// of myfunc() method
parent::myfunc();
echo "myfunc() of child class";
}
}
$class = new child();
$class->myfunc();
?>The output is:
myfunc() of parent class
myfunc() of child class