In this tutorial we will show you the solution of how to define constant in PHP, a constant is an identifier for a simple value. The value of constant cannot be changed during the whole script.
To create a PHP constant, a function that is define() is used.
Here, one thing to note that constant a constant name always start with a letter and underscore.
As, other php variables and elements there is no need of $ sign in constant name.
Step By Step Guide On How To Define Constant In PHP :-
Let us see the below example to see how to define constant in php.
<!DOCTYPE html> <html> <body> <?php define("Welcome", "Talkers Code"); echo Welcome; ?> </body> </html>
- First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in.
- Secondly, the <html> tag is used to indicate the beginning of an HTML document.
- As above now <head> tag is used to contain information about web page. In this tag a <title> tag is used which helps us to specify a webpage title. Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
- Here, then we create a body tag. All the content which we want to show on browser’s screen or display is always written inside this codes.
- Here, as we know that constants are that whose values does not change over whole program. These are global in nature and can be accessed within entire script. Constants always start with an underscore and letter and we do not use $ sign in case of constants.
- Here, as we see in codes to create a constant we use define() function. We can also say that define is used to define constants in php and it has three attributes that are name, value and case-insensitive.
- Mainly the case-insensitiveness is false and optional. In above example, we use two attributes that are name and value. As you see the name above defined is Welcome and value is Talker Code.
- The last one is case-insensitive, we don’t use it here so its value considered in false. In next line, we just print the value of constant by using its name and echo in php. We can also able to create an array using constants. Let us below see the example how to create an array using constant and print them using php. Here, is the code - <?php define("cars", ["Tesla","Audi","Mercedes"]); echo cars[2]; ?>
- At last, the <body> and <html> tags are closed with </body> and </html> respectively.
Conclusion :-
At last in conclusion, here we can say that with the help of this article we are able to understand how to define constant in php.
I hope this tutorial on how to define constant in PHP helps you and the steps and method mentioned above are easy to follow and implement.