Scope Resolution operator in PHP
Last Updated :
21 Jul, 2021
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.
PHP
<?php
class democlass {
const PI = 3.14;
}
echo democlass::PI;
?>
|
Output:
3.14
Example 2: Three special keywords self, parent, and static are used to access properties or methods from inside the class definition.
PHP
<?php
class demo{
public static $bar =10;
public static function func(){
echo static :: $bar . "\n" ;
}
}
class Child extends demo{
public static $bar =20;
}
demo::func();
Child::func();
?>
|
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.
PHP
<?php
class demo{
public function myfunc() {
echo "myfunc() of parent class\n " ;
}
}
class child extends demo {
public function myfunc(){
parent::myfunc();
echo "myfunc() of child class" ;
}
}
$class = new child;
$class -> myfunc()
?>
|
Output:
myfunc() of parent class
myfunc() of child class
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...