Thursday, July 4, 2024
HomeLanguagesPhpScope Resolution operator in PHP

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.

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


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(){
  
         // Calling parent's version
         // of myfunc() method
        parent::myfunc();
  
        echo "myfunc() of child class";
    }
}
  
$class = new child;
$class -> myfunc()
  
?>


Output: 

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

 

Nicole Veronica Rubhabha
Nicole Veronica Rubhabha
A highly competent and organized individual DotNet developer with a track record of architecting and developing web client-server applications. Recognized as a personable, dedicated performer who demonstrates innovation, communication, and teamwork to ensure quality and timely project completion. Expertise in C#, ASP.Net, MVC, LINQ, EF 6, Web Services, SQL Server, MySql, Web development,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments