DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on • Updated on

What the heck is :: in php?? (aka the scope resolution operator)

:: is what you call the scope resolution operator.

We use this to access constants and static properties, functions

Here's some code , for lack of better words

<?php

class FirstClass{

    const EXAMPLE = "I AM CONSTANT";

    public static function test(){
        echo self::EXAMPLE;
    }
}

?>

Say you wanted to execute the test() method outside the firstClass how would you do it? We use that "scope resolution operator" and it is used as follows:

$a = FirstClass::test();
echo $a;

And then say we write another class extended

<?php
class SecondClass extends FirstClass{

    public static $staticProperty = "I AM STATIC";

    public static function anotherTest(){
        echo parent::EXAMPLE;
        echo self::$staticProperty;
    }

}
?>

Even inside the function anotherTest() we can see that :: used.

Instead of using $this->staticProperty; we said self::$staticProperty, and this is because the staticProperty is actually a static property with the static keyword used. :)

Okay hope this is clear, so before closing can I ask a question. How would you access function anotherTest() from outside the class 'secondClass'?

Answer is

echo SecondClass::anotherTest();

Please note when you echo it prints out what is returned from that function. in this case it will return "I AM CONSTANT" AND "I AM STATIC"

Thanks for reading !

Latest comments (0)