Custom Search

OOPS in PHP 5 Tutorial - Defining Class Constants

In PHP5 you can defines class level constants that will not change its value within the class scope. For using class constants PHP5 have introduced a new Keyword “const“. Only a string or numeric value can be assigned to a constant. Arrays, Objects and expressions cannot be assigned to a constant. A class constant can only be accessed via the scope resolution operator (::) executed on the class name.





Example 1 - Basic class constants demo

< ?
class customer
{
     const TYPES = "Anything";
}
$a = new Customer();
echo "Types are : " . $a->TYPES;
?>

Output: “Types are : ”
Explanation: As discussed earlier about accessing class constants using only scope resolution operator the above example will not give “Anything” as the output as we are not using Scope Resolution Operator.

Example 2 - Another Basic class constants demo

< ?
class Customer
{
     const TYPES = "Anything";
     public $TYPES = 12345;
}
$a = new Customer();
echo "Types are : " . $a->TYPES;
?>

Output: “Types are : 12345″
Explanation: As discussed earlier about accessing class constants using only scope resolution operator the above example will not give “Anything” as the output as we are not using Scope Resolution Operator. But we have also declared an public variable TYPES having values 12345 so the program will output 12345 because we have used “->” operator.

Example 3 - Some Twist to class constants demo

< ?
class Customer
{
         const TYPES = "Anything";
         public $TYPES;
 
         public function __construct()
         {
              $this->TYPES = 12345;
         }
}
 
$a = new Customer();
echo "Types are : " . $a->TYPES;
echo "Types are : " . Customer::TYPES;
?>

Output: Types are : 12345
Types are : Anything
Explanation: Here it output data for both the varaiable as we are calling it separately using separate operator.

Similar Posts

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)