PHP – Class Constants

PHP allows an identifier in a class to be defined as a “class constant” with a constant value, the one that remains unchanged on a per class basis. To differentiate from a variable or property within class, the name of the constant is not prefixed with the usual “$” symbol and is defined with the “const” qualifier. Note that a PHP program can also have a global constant created using the define() function.

The default visibility of a constant is public, although other modifiers may be used in the definition. The value of a constant must be an expression and not a variable, nor a function call/property. The value of a constant is accessed through the class name using the scope resolution operator. Inside a method though, it can be referred to through self variable.

classSomeClass{constCONSTANT='constant value';}echoSomeClass::CONSTANT;

Constant names are case sensitive. Conventionally, the names of constants are in upper case.

Example

This example shows how a Class Constant is defined and accessed −

<?php
   class square {
      const PI=M_PI;
      var $side=5;
      function area() {
         $area=$this->side**2*self::PI;
         return $area;
      }
   }
   $s1=new square();
   echo "PI=". square::PI . "\n";
   echo "area=" . $s1->area();
?>

It will produce the following output −

PI=3.1415926535898
area=78.539816339745

Class Constant as Expression

In this example, the class constant is assigned an expression −

<?php
   const X = 22;
   const Y=7;

   class square {
      const PI=X/Y;
      var $side=5;
      function area() {
         $area=$this->side**2*self::PI;
         return $area;
      }
   }
   $s1=new square();
   echo "PI=". square::PI . "\n";
   echo "area=" . $s1->area();
?>

It will produce the following output −

PI=3.1428571428571
area=78.571428571429

Class Constant Visibility Modifiers

Take a look at the following example −

<?php
   class example {
      const X=10;
      private const Y=20;
   }
   $s1=new example();
   echo "public=". example::X. "\n";
   echo "private=" . $s1->Y ."\n";
   echo "private=" . $example::Y ."\n";
?>

It will produce the following output −

public=10
PHP Notice:  Undefined property: example::$Y in  line 11

private=
PHP Fatal error:  Uncaught Error: Cannot access private const example::Y

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *