How to Use 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 codes and blocks in classes, objects, and so on.

With the scope resolution operator, an identifier is often used.

Below, you can find several examples of using the scope resolution operator.

Watch a course Learn object oriented PHP

Defining Constants Inside a Class

In this example, we demonstrate how to define constants within a class:

<?php

class democlass
{
  const PI = 3.14;
}

echo democlass::PI;

?>

The output is the following:

  3.14

Accessing 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

// 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 
  20

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 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();

?>

Resolut

myfunc() of parent class
myfunc() of child class