JavaScript Tutorial

Constants

A constant is an identifier whose value cannot be changed once it is declared in the program.

Rules for declaring a constant

  • Constants are case-sensitive and conventionally are always UPPERCASE.
  • A valid constant name always starts with a letter or an underscore(_) and is followed by any number of letters, numbers and underscores.
  • define() function is used to define a constant.
  • Constant can be accessed by writing its name or by calling constant() function if you want to obtain a constant value dynamically.
  • PHP constants are global and can be used throughout the program.

Syntax to declare a constant

declare(name, value, case-insensitive);

Syntax parameters explanation:

name: name of the constant.
value: value of the constant.
case-insensitive: specifies whether the constant name would be case sensitive or not. By default its value is false.

Code example

Php constant arrays

Array constant can also be created using define() function.

Code example

Php magic constants

In PHP, the constants who change themselves depending upon the way they are used are known as Magic Constants. There are nine such constants in PHP. Unlike other constants magical constants are resolved at compile time. These are case-insensitive constants. Magical constants are as listed below:

Name

Description

__LINE__

Current line number of the file.

__FILE__

The full path and filename of the file. If it is used inside an include, it will return the included file.

__DIR__

The directory of the file. If it is used inside an include, it will return the directory of the included file.

__FUNCTION__

The function name.

__CLASS__

The class name. It also includes the namespace in which the class was declared.

__TRAIT__

The trait name. It also includes the namespace in which the trait was declared.

__METHOD__

The method name.

__NAMESPACE__

Name of the current namespace.

ClassName :: class

Fully qualified class name.

Go back to Previous Course