Constants in PHP object oriented PHP5

  • 2020-03-31 20:42:09
  • OfStack

The constants defined by const in PHP5 do not require a $modifier, unlike the way variables are defined. Const PI = 3.14; That's fine.
Constant names defined with const are generally capitalized, which is a convention in any language.
It is also a convention to use _ join if the constant defined consists of more than one word.
For example, name something like MAX_MUMBER. A good naming method, is the programmer must pay attention to.
Constants in a class are used like static variables, except that their values cannot be changed. We call this constant using the class name :: constant name.


<?
//Declare a final class Math
class Math{
      const  PI = 3.14;      
      public function __toString(){
          return " This is a Math Class. ";
      }
      //There's a way to figure out the area of a circle, using the Const constant,
      //Note the methods used, which are similar to static variables.
      public final function areaOfCircular($r){
          return $r * $r * self::PI ;
      }  
      public final function max($a,$b){
          return $a > $b ? $a : $b ;
      }   
}
echo Math::PI ;
?>

Program running results:
 3.14 

An error will occur when trying to assign values to constants defined by const.

<?
//Declare a final class Math
class Math{
      const  PI = 3.14;      
      public function __toString(){
          return " This is a Math Class. ";
      }
      //There's a way to figure out the area of a circle, using the Const constant,
      //Note the methods used, which are similar to static variables.
      public final function areaOfCircular($r){
          return $r * $r * self::PI ;
      }  
      public final function max($a,$b){
          return $a > $b ? $a : $b ;
      } 
      public function setPI($a){
          self::PI  = 3.1415;
      }
}
echo Math::PI ;
?>

Program running results:
Parse error: parse error in E:PHPProjectstest.php on line 17 

Related articles: