constant() in PHP
We can get the value of a constant by using constant() function in PHP
Let us try one example.
If the constant does not exist then warning message will be generated while using this function
echo constant('PATH'); // output is J:/php_files/
Declaring a constant
We can declare a constant by using define() function in PHP. Here is the syntax
Define( 'Constant', Value);
Let us start with some examples.
In the above code the 2nd output does not show the data actually stored as our declared constants are case sensitive by default. To make them case insensitive we have to use another optional parameter case_insensitive set to TRUE
echo FNAME; // output : Alex
echo Fname; // output : Fname
We can't use hyphens while declaring any constants but we can use underscores
echo Fname; // output : Alex
echo F-name; // output : 0
The difference between constant and variable is the data stored inside a constant is not changed throughout the execution of the program. Whereas variables can be assigned to different values at various stage of the program.
Checking existence of a constant : defined()
Before using any constants in our script we can check if it exist or not by using defined() function. We will get Ture of False as return from this function. Here is an example.
In above code we have first declared a constant and then in 2nd line checked the existence so the if condition will return TRUE. By removing the first line we will get FALSE and else condition will execute.
echo "Constant SITE exist";
echo "Constant doesn't exist";}
Where to use constant and where to use variable
When we don't expect the value to change throughout the execution of script then we should use constants. Readability of code is the main advantage of using constants in our scripts. Here are some examples of constants.
Note that there is no hard rule that you must use constants in your scripts.
Number of seconds in one minute
We know the above values will not change during execution of the script. In some cases we have to use variables like this.
Interest Rate of Bank for the maturity calculation
Time of adding the record to database table ( to prevent recursive posting within short interval by spammer )
Initial deposit amount in Bank
While using the constant name always keep them within quotes like defined('SITE')
To check the variables we use isset()
To check the functions we use function_exists()
To check the constants we use defined()
Be the first to post comment on this article :
What is the most important factor of a web site