PHP Constants

Constants are similar to variables, but once defined, their values cannot be changed or undefined throughout the script.

Tutorials dojo strip



PHP Constants

A constant is a name for a simple value that remains the same during the script’s execution. A valid constant name starts with a letter or underscore (without a $ sign). Unlike variables, constants are automatically global across the entire script.




Creating a PHP Constant

To create a constant, use the define() function.

Syntax

PHP

Parameters:

  • name: Specifies the constant’s name.
  • value: Specifies the constant’s value.

Example: Case-Sensitive Constant

PHP




Using the const Keyword

You can also create a constant using the const keyword.

Example: Case-Sensitive Constant with const Keyword

PHP

const vs. define()

  • const cannot be created inside a block scope, such as within a function or an if statement.
  • define can be created inside a block scope.




PHP Constant Arrays

From PHP 7 onwards, you can create an array constant using the define() function.

Example: Creating an Array Constant

PHP




Constants are Global

Constants are automatically global and can be used across the entire script.

Example: Using a Constant Inside a Function

PHP

Tutorials dojo strip