CONSTANT


computer apg

As a general definition of constant we have:

is symbolic name associated with an associated value which CAN NOT be changed and is automatically global across the entire script.

The name of a constant NEVER STARTS with a $ and the first character can NEVER be numeric.

Therefore, constants cannot be changed once it is declared.

Class constants can be useful if you need to define some constant data within a class.

Class constants are case-sensitive.

However, it is recommended to name the constants in all UPPERCASE letters.


1. We can access a constant from outside the class by using the class name followed by the scope resolution operator, ::, followed by the constant name
or
2. we can access a constant from inside the class by using the self keyword followed by the scope resolution operator, ::, followed by the constant name.



 const 


A class constant is declared inside a class with the const keyword.



  1 EXERCISE   

<?php

class Dwarfs {
  public 
$name;
  public 
$behavior;
  
  const 
DMESSAGE "A real famous dwarf:<br><br>";
  
  public function 
__construct($name$behavior
  {
    
$this->name $name;
    
$this->behavior $behavior;
  }
  public function 
intro() 
  {
    echo 
$this->name '<br>';
    echo 
$this->behavior '<br><br>';
  }
}

/* The class Dwarf is inherited from the class Dwarfs */

class Dwarf extends Dwarfs 
{
  public function 
message() 
  {
    echo 
Dwarf::DMESSAGE;
  }
}
$rd '1 - Tyrion Lanister.';
$bh '2 - played by Peter Dinklage.';
$Dwarf = new Dwarf($rd$bh);
$Dwarf->message();
$Dwarf->intro();
     
?>

 RESULT   

A real famous dwarf:

1 - Tyrion Lanister

2 - played by Peter Dinklage


  2 EXERCISE   

<?php

class Dwarfs {
  public 
$name;
  public 
$behavior;
  
  const 
DMESSAGE "A real famous dwarf:<br><br>";
  
  public function 
__construct($name$behavior
  {
    
$this->name $name;
    
$this->behavior $behavior;
  }
  public function 
intro() 
  {
    echo 
$this->name '<br>';
    echo 
$this->behavior '<br><br>';
  }
}

/* The class Dwarf is inherited from the class Dwarfs */

class Dwarf extends Dwarfs 
{
  public function 
message() 
  {
    echo 
self::DMESSAGE;
  }
}
$rd '1 - Tyrion Lanister.';
$bh '2 - played by Peter Dinklage.';
$Dwarf = new Dwarf($rd$bh);
$Dwarf->message();
$Dwarf->intro();
     
?>

 RESULT   

A real famous dwarf:

1 - Tyrion Lanister

2 - played by Peter Dinklage


Using the self keyword