In this lesson, you will learn about PHP Constant, constant arguments, and the constant function, along with examples to better understand the topic.
As the name indicates, a constant is an identifier that, once defined, cannot be modified through the program’s execution. By convention, the constant’s name begins with a letter or underscore, followed by any numbers, underscores, or letters. Constant has some properties like it is case-sensitive, always uppercase, and cannot be undefined. Constants have, by default, global scope throughout the whole program.
The First question arises. Why would you use such a value if you couldn’t change it by running your program once it is defined? The logic of constants implies database configuration settings, magic numbers, magic strings, etc. Many people advise against making database settings constant. Not only will it be challenging to test your program, but editing and deploying a program where you need to change the configuration is also unusual.
Functions are used to set and get the value of constants.
To create a constant, use the define()
keyword to restore value and name. Unlike variables, you do not need to have a constant with a $
, and you must specify its name. Constants have a three-parameter syntax, but you can also set whether or not the constant name should be case-sensitive. The define()
function takes false by default.
define(constant name, constant value, case-insensitive option)
1 – Define(): Create a constant with one argument and displays a warning message
Example
<?php define("PARAMETER" ); ?>
Output
In some cases, PHP will display a warning message.
2 – Define(): Create constant with 2 arguments
The second argument only accepts scalar data (boolean, integer, float, and String)
Example
<?php // Invalid constant names define("9VAR_NAME6", "INVALID VARIABLE NAME"); echo 9VAR_NAME6; ?>
Output
Parse error: syntax error, unexpected ‘VAR_NAME6’ (T_STRING), expecting ‘,’ or ‘;’ in C:\xampp\htdocs\project\hello.PHP on line 3
Example
<?PHP // Considered valid but in foreseeable future it might crash // your PHP program if declared invalid echo " __VAR_NAME9__ Not recommended as a variable name "; echo "<br>"; echo "<br>"; define("__VAR_NAME9__", "CAN BE INVALID VARIABLE NAME IN FORESEEABLE FUTURE"); echo __VAR_NAME9__; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; echo "Scalar Data (Boolean, Integer, Float, and String)"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; //Definition of constant string variable echo " Definition of String constant = "; define("VAR_NAME1", "I’m a string variable!!!!"); echo VAR_NAME1; echo "<br>"; //Definition of constant integer variable echo " Definition of integer constant = "; define("VAR_NAME2", 1131315479754); echo VAR_NAME2; echo "<br>"; //Definition of constant float variable echo " Definition of float constant = "; define("VAR_NAME3", 897415.547894); echo VAR_NAME3; echo "<br>"; //Definition of constant boolean variable echo " Definition of boolean constant = "; define("VAR_NAME4", true); echo VAR_NAME4; echo "<br>"; echo " Definition of boolean constant = "; define("VAR_NAME5", false); echo VAR_NAME5; echo "<br>"; ?>
Output
__VAR_NAME9__ Not recommended as a variable name``` CAN BE INVALID VARIABLE NAME IN FORESEEABLE FUTURE ---------------------------------------- Scalar Data (Boolean, Integer, Float, and String) ---------------------------------------- Definition of String constant = I'm a string variable!!!! Definition of integer constant = 1131315479754 Definition of float constant = 897415.547894 Definition of boolean constant = 1 Definition of boolean constant =
Boolean with the false value will return 0; it will not be displayed. In the next example, we will create a constant with a case-sensitive name:
3 – Define(): Create constant with 3 arguments
Create a constant with a case-sensitive name
Example
<?php echo "Case-insensitive Example"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; //true argument make the VAR_NAME1 case-insensitive define("VAR_NAME1", "PHP is an excellent programming language!!!!", true); echo var_name1; echo "<br>"; //false argument make the VAR_NAME2 case-sensitive define("VAR_NAME2", "PHP is an excellent programming language!!!!", false); echo var_name2; echo "<br>"; ?>
Output
Case-insensitive Example ---------------------------------------- PHP is an excellent programming language!!!! Warning: Use of undefined constant var_name2 - assumed 'var_name2' (this will throw an Error in a future version of PHP) in C:\hello.PHP on line var_name2
The same line of code in the above example displays a different result. VAR_NAME1
becomes case-insensitive and thus accessible through var_name1
. VAR_NAME2
becomes case-sensitive with false argument, thus showing the Warning of undefined constant through small case var_name2
.
Example
<?php echo "Scope of Constant Example"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; //Constants are automatically global and can be utilized through the program. define("VAR_NAME1", "This is a great PHP Tutorial!!!!"); $VAR_NAME2 = "This is a great PHP Tutorial!!!!"; function constantFunc() { echo VAR_NAME1; echo "<br>"; echo $VAR_NAME2; echo "<br>"; } constantFunc(); ?>
Output
Scope of Constant Example ---------------------------------------- This is a great PHP Tutorial!!!! Notice: Undefined variable: VAR_NAME2 in C:\hello.PHP on line 12
Constants are, by default, public. However, the standard variable doesn’t have public scope. A Boolean with a false value will return 0, but it will not be displayed. In the above example, VAR_NAME1 and VAR_NAME2 are assigned the same value at the same level, but the standard variable gives a syntax error.
The function constant()
retrieves a constant’s value if you want to dynamically obtain the constant’s name. This function will return the value of a constant.
constant (string $name)
Using this method is beneficial if you are unfamiliar with the variable’s name. If the constant is not defined, the system will only throw a warning (with NULL) and return the value of the constant. The constant can be the name of an empty string.
Example
<?php echo "Constant() Empty string Example"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; define("", 'This is a great PHP Tutorial!!!!'); echo constant(""); ?>
Output
Constant() Empty string Example ---------------------------------------- This is a great PHP Tutorial!!!!
Example
<?php echo "Constant() Function Example"; echo "<br>"; echo " ---------------------------------------- "; echo "<br>"; //Constant() function is used to get the value of constant using define(). define("VAR_NAME1", 78945); echo VAR_NAME1; echo "<br>"; echo constant("VAR_NAME1"); // same thing as the previous line echo "<br>"; interface interface_Name { const VAR_NAME2 = 'This is a great PHP Tutorial!!!!'; } class class_Name { const VAR_NAME2 = 'This is a great PHP Tutorial!!!!'; } $const = 'VAR_NAME2'; var_dump(constant('interface_Name::' . $const)); echo "<br>"; echo "<br>"; var_dump(constant('class_Name::' . $const)); ?>
Output
Constant() Function Example ---------------------------------------- 78945 78945 string(32) "This is a great PHP Tutorial!!!!" string(32) "This is a great PHP Tutorial!!!!"
If You don’t know the name of the variable but still can access the constant value using the class or interface name:: constant
'interface_Name::'.$const 'class_Name::'.$const :: double colon is used to access the members of interface and class.
The “magic constants,” or predefined PHP constants, vary based on their use. They have a double underscore (__) at the beginning and end. Although they are comparable to other specified constants, they are known as “magic constants” since they alter according to the situation. As opposed to the regular constants, all constants are resolved at compile time.
In PHP, there are nine magic constants. Eight magic constants have double underscores (__) at the beginning and end.
__LINE__ __FILE__ __DIR__ __CLASS__ __TRAIT__ __METHOD_ __FUNCTION__ __NAMESPACE__ ClassName::class
Example
<?php echo "<h2>Constant __LINE__</h2>"; echo "Constant __LINE__ :The current file line number where this constant is used is returned.<br>"; echo "This is " . __LINE__ . " line no<br>"; echo "==================<br>"; echo "<h2>Constant __FILE__</h2>"; echo "Constant __FILE__:This constant returns the full path to the executable file's storage location. The included file's name is displayed as a response if it is used inside the inclusion.<br>"; echo "This is " . __FILE__ . "<br>"; echo "=================="; echo "<h2>Constant __DIR__</h2><br>"; echo "Constant __DIR__: It gives back the complete directory path of the file that was run. Unless it is a root directory, this magic constant does not contain a trailing slash. This constant magic returns a path equivalent to dirname(__FILE__).<br>"; echo "This is " . __DIR__ . "<br>"; echo dirname(__FILE__) . "<br>"; ?> </body> </html>
Output
Constant __LINE__ Constant __LINE__:The current file line number where this constant is used is returned. This is 8 line no ================== Constant __FILE__ Constant __FILE__:This constant returns the full path to the executable file's storage location. The included file's name is displayed as a response if used inside the inclusion. This is /home/l0wLno/prog.PHP. ================== Constant __DIR__ Constant __DIR__:It gives back the complete directory path of the file that was run. Unless it is a root directory, this magic constant does not contain a trailing slash. This constant magic returns a path equivalent to dirname(__FILE__). This is /home/l0wLno /home/l0wLno
I hope I have explained the PHP Constants in a clear and enjoyable way! In the next lesson, you will learn about the Data Types in PHP and their usage.