Scope Resolution Operator

Rumman Ansari   Software Engineer   2020-02-06   5493 Share
☰ Table of Contents

Table of Content:


In PHP, the scope resolution operator is also called Paamayim Nekudotayim which means "double colon" or "double dot twice" in Hebrew. The double colon (::), is a token that allows access to static, constant, and overridden properties or methods of a class.

PHP: Class Constants

  • A special entity that remains fixed on an individual class basis.
  • Constant names are not preceded by a dollar sign ($) like a normal variable declaration.
  • Interfaces may also include constants.
  • When calling a class constant using the $classname :: constant syntax, the class name can actually be a variable.
  • As of PHP 5.3, you can access a static class constant using a variable reference (Example: className :: $varConstant).

Define and using a constant

Syntax



<?php
  class MyClass
  {
  const constant1 = 'PHP Class Constant';
   function PrintConstant() 
   {
       echo  self::constant1 . "<br>";
   }
  }
  echo MyClass::constant1 . "<br>";
  
  $classname = "MyClass";
  echo $classname::constant1 . "<br>"; // As of PHP 5.3.0
  $class = new MyClass();
  $class->PrintConstant();
  echo $class::constant1."<br>"; // As of PHP 5.3.0
 ?>



Output:

The above code will produce the following result-


PHP Class Constant
PHP Class Constant
PHP Class Constant
PHP Class Constant