PHP constant is a name or an identifier for a simple value. A constant value cannot be changed during the execution of the script. By default, a constant is case-sensitive. By convention, constant identifiers are always uppercase. The name of a constant begins with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.
How to Define a Constant?
PHP Constant() Function
This is useful when you want to retrieve the value of a constant, but you do not know its name, i.e. it is stored in a variable.
<?php define("MINSIZE", 50); echo MINSIZE; echo constant("MINSIZE"); // same thing as the previous line ?>
Difference between Variables & Constants
- There is no need to write a dollar sign ($) before writing a constant, whereas one needs to write a dollar($) sign in a variable.
- Constants can't be defined by simple assignment, they can only be defined by using the define() function.
- Constants may be defined and then accessed anywhere within a program without regarding the variable scoping rules.
- Once a constants have been set, they may not be redefined or undefined.
Valid and Invalid Constant Names
// Valid constant names define("ONE", "first thing"); define("TWO2", "second thing"); define("THREE_3", "third thing"); define("__THREE__", "third value"); // Invalid constant names define("2TWO", "second thing");
PHP Magic Constants
PHP makes available five magic constants that changes depending on where they are used. For example, the value of __LINE__ is dependent on the line it is used on in your script.
This special constants are case-insensitive and are as follows -
|Sr.No||Name & Description|
The current line number of the file.
The full path and filename of the file. If used inside an include,the name of the included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path under some circumstances.
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).
Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.
Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.
Thanks for reading and bye for now.