PHP - Constants Defined

PHP - Constants Defined

  • A constant is an identifier (name) for a simple value. That value cannot change during the execution of the PHP script. Constants are case-sensitive. By convention, constant identifiers are always uppercase.
  • The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores,PHP constants should be defined in uppercase letters. 

Note:

Prior to PHP 8.0.0, constants defined using the define() function may be case-insensitive.


PHP constants can be defined by 2 ways:

  1. Using define() function
  2. Using const keyword

PHP constant: define()

     define(name, value, case-insensitive)
  1. name: It specifies the constant name.
  2. value: It specifies the constant value.
  3. case-insensitive: Specifies whether a constant is 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().

Output:

Hello PHP

Create a constant with case-insensitive name:

Output:

Hello PHP
Hello PHP


Output:

Hello PHP
Notice: Use of undefined constant message - assumed 'message' 
in C:\xampp\htdocs\constant.php on line 4

PHP constant: const keyword

PHP introduced a keyword const to create a constant. 
The const keyword defines constants at compile time. 
It is a language construct, not a function. 
The constant defined using const keyword are case-sensitive.

Output:

Hello const by SoftHubSolution PHP

Constant() function

There is another way to print the value of constants using constant() function instead of using the echo statement.

Syntax:

The syntax for the following constant function:

constant (name) ;


Output:

Welcome to SoftHubSolution
Welcome to SoftHubSolution

Post a Comment

Previous Post Next Post