How To Use PHP Constants
Php constant consider the key and value.
PHP constants are name or identifier that can't be changed during the execution of the script. PHP constants can be defined by 2 ways:
- Using define() function
- Using const keyword
PHP constants follow the same PHP variable rules. For example, it can be started with letter or underscore only.
Conventionally, PHP constants should be defined in uppercase letters.
PHP constant method: define()
Let's see the syntax of define() function in PHP.
- define(name, value, case-insensitive)
- name: specifies the constant name
- value: specifies the constant value
- case-insensitive: Default value is false. It means it is case sensitive by default.
Let's see the example to define PHP constant using define().
File: constant.php- <?php
- define("MESSAGE","Hello samadroid PHP");
- echo MESSAGE;
- ?>
Output:
Hello samadroid PHP
- <?php
- define("MESSAGE","Hello samadroid PHP",true);//not case sensitive
- echo MESSAGE;
- echo message;
- ?>
Output:
Hello samadroid PHPHello JavaTpoint PHP
- <?php
- define("MESSAGE","Hello samadroid PHP",false);//case sensitive
- echo MESSAGE;
- echo message;
- ?>
Output:
Hello samadroid PHP Notice: Use of undefined constant message - assumed 'message' in C:\wamp\www\vconstant3.php on line 4 messagee
PHP constant: const keyword
The construction key word is very easy method
The const keyword defines constants at compile time. It is a language construct not a function.
It is bit faster than define().
It is always case sensitive.
File: constant.php- <?php
- const MESSAGE="Hello const by samadroid PHP";
- echo MESSAGE;
- ?>
Output:
Hello const by samadroid PHP