PHP Constant
PHP Constant is also similar to the PHP VAriables but the value of Constant cannot be changed or Constant has a fixed value.
If you want to create a constant then you have to use the “define()” function.
Example 1 – Constant Syntax
<!DOCTYPE html> <html> <head> </head> <body> <?php define("name of constant", "value of constant", "case-sensitive"); echo name; ?> </body> </html>
In the above examples, we have shown how you can create constant in PHP.
Here we are using a define() function. We have to write the name of the constant and value of the constant inside small brackets.
Important Facts About The Constant
- The value of a constant cannot be changed across the script.
- The name of the constant starts with the letters or underscore.
- The scope of constants are global during the entire script.
- The constant name may be case-sensitive. You also decide it may case-sensitive or not.
Note:By default, the constant case-sensitive value is default “false”.
Example 2 – String Constant Example
<!DOCTYPE html> <html> <head> </head> <body> <?php define("World", "Welcome to the Technology World....."); echo World; ?> </body> </html>
In the above examples, we have shown how you can create constant in PHP.
Here we are using a define() function. We have to write the name of the constant and value of the constant inside small brackets.
Here we write the name of the constant is “World” and the value of the constant is “Welcome to the Technology World…..”. Through the echo function, we print the value of constant.
PHP Constant with Case-Sensitive Nature Syntax Code Example
By default the constants are case-sensitive or the value of case-sensitive is false but if you want to change constant from case-sensitive to case-insensitive than you have to apply the value is true.
Example 3 – Case-Sensitive Constant Example
<!DOCTYPE html> <html> <head> </head> <body> <?php define("World", "Welcome to the Technology World.....", false); echo World; define("GOOD", "We have to try to do good work....", false); echo good; ?> </body> </html>
In the above examples, we have 2 constants which or World and GOOD. And both constants are case-sensitive.
But when we apply the echo function we use the lower case to write GOOD so it shows error not print the value on the web page.
Constants are Global
The scope of constants are global during the entire script.Example 4 – Constants are Global Example
<!DOCTYPE html> <html> <head> </head> <body> <?php define("Work", "To do hard work...."); function myWork() { echo Work; } myWork(); ?> </body> </html>
In the above examples, we create a constant of the name “Work” and a function “myWork()”. The constant will be echo inside the function even the constant declared outside the function.