Scope Resolution Operator In PHP

Introduction

This article explains the scope resolution operator in OOP using PHP5. The scope resolution operator, or in less complicated terms, the double colon, may be a token that permits access to static, constant, and overridden properties or ways of a category. When referencing these things from outside the category definition, use the name of the category. As of PHP 5.3, it is possible to reference the category employing a variable. The variable can't be a keyword such as the self keyword, parent and static keyword. At first, it looks like an odd selection for naming a double-colon.

The most common use for scope resolution is with the pseudo-class "parent". As an example, if you wish a child object to determine its parent's "__construct()" operater then you use "parent::__construct()". The scope resolution operator sometimes is useful to refer to functions and variables in base classes.

Example

<?php

class demo {

    function test() {

        echo "this own function demo::test().'<br>'";

    }

}

class newclass extends demo {

    function test() {

        echo "this is modified functio newclass::test().'<br>'";

        demo::test();

    }

}

demo::test();

$a = new newclass;// include the outside demo class

$a->test();

?>

Output

scope resolution operator

Example

Three special keywords self, parent and static square measure won't access properties or ways from within the category.

<?php

class demo

{

    const static_value = 'A constant value';

}

$demoname = 'demo';

echo $demoname::static_value."<br>";

echo demo::static_value."<br>";

?>

 

Output


outsie the class

Example

In this example we use "demo" outside the class. When an associated extending category overrides the oldsters definition of a technique, PHP won't determine the parent's technique. It's up to the extended category to determine whether or not the parent's technique is termed. This additionally applies to Constructors and Destructors, Overloading, and Magic technique definitions.

<?php

include 'demo.php';// include the outside demo class

class newclass extends demo// extend the outside demo class

{

    public static $var = 'static var';

    public static function exa()

    {

        echo parent::static_value . "<br>";

        echo self::$var ."<br>";

    }

}

$demoname = 'newclass';

echo $demoname::exa();

newclass::exa();

?>

 

Output


inside the class


Example

This example show calling a parent's method.

 

<?php

class demo

{

    protected function hello()

       {

        echo "demo::hello()"."<br>";

    }

}

class newclass extends demo

{

    // Override parent's definition

    public function hello()

    {

        // But still call the parent function

        parent::hello();

        echo "newclass::hello()"."<br>";

    }

}

$test = new newclass();

$test->hello();

?>


Output

calling parent method