Scope Resolution operator in PHP

The scope resolution operator also known as Paamayim Nekudotayim or more commonly known as the double colon is a token that allows access to static, constant, and overridden properties or methods of a class.

It is used to refer to blocks or codes in context to classes, objects, etc. An identifier is used with the scope resolution operator. The most common example of the application of the scope resolution operator in PHP is to access the properties and methods of the class.

The following examples show the usage of the scope resolution operator in various scenarios.

Example 1: This type of definition is used while defining constants within a class.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
   
class democlass {
    const PI = 3.14;
}
   
echo democlass::PI;
   
?>

chevron_right


Output:



3.14

Examlpe 2: Three special keywords self, parent, and static are used to access properties or methods from inside the class definition.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
   
// Declaring parent class
class demo{
   
    public static $bar=10;
   
    public static function func(){
   
        echo static::$bar."\n";
    }
}
   
// Declaring child class
class Child extends demo{
   
    public static $bar=20;
   
}
   
// Calling for demo's version of func()
demo::func();
   
// Calling for child's version of func()
Child::func();
   
?>

chevron_right


Output:

10 
20

Example 3: When an extending class overrides its parent’s function, the compiler calls the child class’s version of the method but it is up to the child class to call its parent’s version of the method.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
   
class demo{
   
    public function myfunc() {
        echo "myfunc() of parent class\n ";
    }
}
   
class child extends demo {
   
    public function myfunc(){
   
         // Calling parent's version 
         // of myfunc() method
        parent::myfunc();
   
        echo "myfunc() of child class";
    }
}
   
$class = new child;
$class -> myfunc() 
   
?>

chevron_right


Output:

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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.