Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Scope Resolution Operator (::)
In PHP, the double colon :: is defined as Scope Resolution Operator. It is used when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator. This operator is also called Paamayim Nekudotayim, which in Hebrew means double colon.
Syntax
<?php
class A{
const PI=3.142;
static $x=10;
}
echo A::PI;
echo A::$x;
$var='A';
echo $var::PI;
echo $var::$x;
?>
3.142103.14210
Using self Keyword Inside Class
To access class level items inside any method, keyword self is used −
<?php
class A{
const PI=3.142;
static $x=10;
static function show(){
echo self::PI . " " . self::$x;
}
}
A::show();
?>
3.142 10
Accessing Parent Class Methods
If a parent class method is overridden by a child class and you need to call the corresponding parent method, it must be prefixed with parent keyword and scope resolution operator −
<?php
class testclass{
public function sayhello(){
echo "Hello World
";
}
}
class myclass extends testclass{
public function sayhello(){
parent::sayhello();
echo "Hello PHP";
}
}
$obj=new myclass();
$obj->sayhello();
?>
Hello World Hello PHP
Key Points
| Context | Keyword | Usage |
|---|---|---|
| Outside class | ClassName | ClassName::constant |
| Inside class | self | self::$property |
| Child class | parent | parent::method() |
Conclusion
The scope resolution operator (::) provides access to static properties, constants, and methods. Use self:: within the same class and parent:: to call overridden parent methods in inheritance.
