PHP Constants
A constant is a name or an identifier that can’t be changed during the execution of the script (except magic constants). A valid PHP constant name starts with a letter or underscore (no $ sign before the constant name).
There are two way to defined PHP Constants which is given below:
- Using define()function
- Using const keyword
1. Using define() function
Syntax:
define(name, value, case-insensitive)
Where:
- name: denote the constant name
- value: denote the constant value
- case-insensitive: Default value is false. So we can say it is case sensitive by default.
Example
with a case-sensitive name:
<?php define("CHEERFUL", "Welcome to Netzole.com!"); echo CHEERFUL; ?>
Output:
Welcome to Netzole.com!
Example
with a case-insensitive name:
<?php define("CHEERFUL", "Welcome to Netzole.com!", true); echo cheerful; ?>
Output:
Welcome to Netzole.com!
PHP Constant Arrays
Example
with a Array constant:
<?php define("cars", [ "Verna", "BMW", "Toyota" ]); echo cars[1]; ?>
Output:
Verna
2. Using const keyword
The const keyword defines constants at compile time. It is a language construct not a function.It is bit faster than define() and It is always case sensitive.
Example
with a case-sensitive name:
<?php const MESSAGE="Welcome to Netzole.com!"; echo MESSAGE; ?>
Output:
Welcome to Netzole.com!