Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Constants

PHP Constants

A constant is an identifier (name) for a simple value that cannot be changed during the execution of the script.

A valid constant name must begin with a letter or an underscore (without the $ sign).

Note: Unlike variables, constants are automatically global throughout the entire script.

Create a PHP Constant

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

Syntax

define(name, value, case-insensitive);

Parameters:

  • name: Specifies the name of the constant.
  • value: Specifies the value of the constant.
  • case-insensitive: Indicates whether the constant name should be case-insensitive. The default is false. Note: Defining case-insensitive constants was deprecated in PHP 7.3, and PHP 8.0 only accepts false; using true will generate a warning.

Example

Create a constant with a case-sensitive name:

define("GREETING", "Welcome to W3Schools.com!");
echo GREETING;

Example

Create a constant with a case-insensitive name:

define("GREETING", "Welcome to W3Schools.com!", true);
echo greeting;

PHP const Keyword

You can also define a constant using the const keyword.

Example

Create a constant using the const keyword:

const MYCAR = "Volvo"
echo MYCAR;

const vs. define()

  • const is always case-sensitive.
  • define() offers a case-insensitive option.
  • const cannot be defined inside another block scope, such as within a function or an if statement.
  • define() can be used within other block scopes.

PHP Constant Arrays

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

Example

Define an array constant:

define("cars", [
 "Alfa Romeo",
 "BMW",
 "Toyota"
]);
echo cars[0];

Constants are Global

Constants are automatically global and can be accessed throughout the entire script.

Example

This example demonstrates using a constant inside a function, even though it is defined outside the function.

define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
 echo GREETING;
}
myTest();