PHP Class Constants


Introduction

PHP allows an identifier in a class to be defined to have a constant value, the one that remains unchanged on a per class basis.To differentiate rom a variable or property wthin class, name of constant is not prefixed with $ symbol and is defined with const qualifier.

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

Syntax

class SomeClass{
   const CONSTANT = 'constant value';
}
echo SomeClass::CONSTANT;

Constant names are case sensitive. Conventionally, name of constant is given in upper case

Class Constant example

This example shows how a Class Constant is defined and accessed

Example

 Live Demo

<?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 . "
"; echo "area=" . $s1->area(); ?>

Output

This will produce following result. −

PI=3.1415926535898
area=78.539816339745

Class Constant as expression

In this example, class constant is assigned an expression

Example

 Live Demo

<?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 . "
"; echo "area=" . $s1->area(); ?>

outer

This will produce following result. −

PI=3.1428571428571
area=78.571428571429

Class constant visibility modifiers

Example

 Live Demo

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

Output

This will produce following result. −

1public=10
PHP Notice: Undefined property: example::$Y in line 11
private=PHP Fatal error: Uncaught Error: Cannot access private const example::Y

Updated on: 18-Sep-2020

497 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements