Use of Scope Resolution Operator in PHP

 






 (::)  in php defined as Scope Resolution Operator. Just like a double colon. Normally Scope Resolution Operator used when we want to access Contstant, static and overriiden methods and properties of a class.

So, the summary is using (::) you can access properties and methods in a class without instantiated it. see example below:

<?php
class test{
public function hello(){
echo "Hello World \n";
}
}

echo test::hello(); //without instantiate class, using Scope Resolution Operator
$hello1=new test; // instantiate class, normal usage
$hello1->hello();

?>

But the main purpoe of using  Scope Resolution Operator(::) is when we want to access Contstant, static and overriiden methods and properties of a class. see example below:

<?php
class test{
const PI=3.1416; 
        static $i=6;
}

echo test::PI; //constant property
echo test::$i; //static property

?>

Now to access class properties inside method , we need to use self see example below:

<?php
class test{
const PI=3.1416; 
        static $i=6;
        static function show(){
              echo self::PI; //using self to access class properties
              echo '  ';
              echo self::$i;
   }
}

echo test::show();

?>

In another case, if your method is overridden by child class and you need to call the parent class method just use parent keyword. see the example below:


<?php
class test{
public function hello(){
echo "Hello World \n";
}
}
class mytest extends test{
public function hello(){
        parent::hello(); //using parent to access parent class method
echo "Hello beautiful world";
}
}

$world1 =  new mytest();
$world1->hello();

?>


Thnak you and enjoy :)

Post a Comment (0)
Previous Post Next Post