PHP Constants

PHP Constants


A single value identifier is referred to as a constant (name). It cannot change the value while the script is running.

A valid constant name begins with a letter or underscore (there is no $ sign preceding the constant name).

Note :- Contrary to variables, constants automatically reach the whole script globally.

You can also search for these topics, constants in php, php constants example, php constants type, use of php constant.

Create a PHP Constant

Use the define() method to build a constant.

Syntax :-

define(name, value, case-insensitive).

Parameters :

  • name: Specifies the name of the constant.
  • value: Specifies the value of the constant.
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.

Exampe 1 :- Create a constant with a case-sensitive name.

<?php
define("Message", "Welcome to simmanchith.com!");
echo Message;
?>

Output :-

Welcome to simmanchith.com!

Example 2 :- Create a constant with a case-insensitive name:

<?php
define("MESSAGE", "Welcome to simmanchith.com!", true);
echo message;
?>

Output :-

Welcome to simmanchith.com!



You can also search for these topics, create a php constant, explain define() method in php, parameter constant in php, php constant syntax, php case-sensitive, php create constant array, php create predefined constant, php create dynamic constant, php create a constant syntax.

Constants are Global

Constants are globally automated and can be used throughout the script.

Example :- This example utilizes a function constantly, even though it is specified outside of the function :

<?php
define("GREETING", "Welcome to simmanchith.com!");
function myTest() {
  echo GREETING;
}
 
myTest();
?>

Output :-

Welcome to simmanchith.com!



You can also search for these topics, arrays are global, global contants in php, constants are global example using php.

PHP Constant Arrays

The define() method in PHP7 allows you to build an Array constant.

Example :- Create an Array constant:

<?php
define("cars", [
  "Alfa Romeo",
  "BMW",
  "Toyota"
]);
echo cars[0];
?>

Output :-

Alfa Romeo

You can also search for these topics, php constant array, example of array constant in php , constant array example in php, how to create array constant using php.