跳转到主要内容

Constants

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren't actually constants). Constants are case-sensitive. By convention, constant identifiers are always uppercase.

[!NOTE] Prior to PHP 8.0.0, constants defined using the define function may be case-insensitive.

[!NOTE] As of PHP 8.5.0, redeclaring an already-defined constant is deprecated.

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. As a regular expression, it would be expressed thusly: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$

It is possible to define constants with reserved or even invalid names, whose value can only be retrieved with the constant function. However, doing so is not recommended.

ENTITY

Valid and invalid constant names

<?php

// Valid constant names
define("FOO",     "something");
define("FOO2",    "something else");
define("FOO_BAR", "something more");

// Invalid constant names
define("2FOO",    "something");

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__", "something"); 

    

[!NOTE] For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 128 through 255 (0x80-0xff).

Like ENTITY, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope. For more information on scope, read the manual section on variable scope.

[!NOTE] As of PHP 7.1.0, class constant may declare a visibility of protected or private, making them only available in the hierarchical scope of the class in which it is defined.

Syntax

Constants can be defined using the const keyword, or by using the define-function. While define allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.

When using the const keyword, only scalar (bool, int, float and string) expressions and constant arrays containing only scalar expressions are accepted. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

The value of a constant is accessed simply by specifying its name. Unlike variables, a constant is not prepended with a $. It is also possible to use the constant function to read a constant's value if the constant's name is obtained dynamically. Use get_defined_constants to get a list of all defined constants.

[!NOTE] Constants and (global) variables are in a different namespace. This implies that for example ENTITY and $TRUE are generally different.

If an undefined constant is used an Error is thrown. Prior to PHP 8.0.0, undefined constants would be interpreted as a bare word string, i.e. (CONSTANT vs "CONSTANT"). This fallback is deprecated as of PHP 7.2.0, and an error of level E_WARNING is issued when it happens. Prior to PHP 7.2.0, an error of level E_NOTICE has been issued instead. See also the manual entry on why $foo[bar] is wrong (unless bar is a constant). This does not apply to (fully) qualified constants, which will always raise a Error if undefined.

[!NOTE] To check if a constant is set, use the defined function.

These are the differences between constants and variables:

  • Constants do not have a dollar sign ($) before them;

  • Constants may be defined and accessed anywhere without regard to variable scoping rules;

  • Constants may not be redefined or undefined once they have been set; and

  • Constants may only evaluate to scalar values or arrays.

Defining Constants

<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // Emits an Error: Undefined constant "Constant"
               // Prior to PHP 8.0.0, outputs "Constant" and issues a warning.

     

Defining Constants using the const keyword

<?php
// Simple scalar value
const CONSTANT = 'Hello World';

echo CONSTANT . "\n";

// Scalar expression
const ANOTHER_CONST = CONSTANT . '; Goodbye World';
echo ANOTHER_CONST . "\n";

const ANIMALS = array('dog', 'cat', 'bird');
echo ANIMALS[1] . "\n"; // outputs "cat"

// Constant arrays
define('ANIMALS_DEF', array(
    'dog',
    'cat',
    'bird'
));
echo ANIMALS_DEF[1] . "\n"; // outputs "cat"

     

[!NOTE] As opposed to defining constants using define, constants defined using the const keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements or try/catch blocks.

ENTITY

ENTITY ENTITY
8.5.0 Added support for type casts (e.g. (int), (string)) in constant expressions. Also added support for Closures and first-class callables in constant expressions.

ENTITY

Class Constants

Predefined constants

PHP provides a large number of predefined constants to any script which it runs. Many of these constants, however, are created by various extensions, and will only be present when those extensions are available, either via dynamic loading or because they have been compiled in.

Magic constants

Magic constants are keywords that are replaced with information about their own location in the source code: their file and line, and the function, class, trait, namespace, or property hook enclosing them. Despite their name, they are not actual constants: defined and constant do not recognize them, and a constant of the same name created with define does not affect them. They are case-insensitive. When used outside of the relevant context (e.g. __CLASS__ outside of a class), they are replaced with an empty string.

ENTITY ENTITY
__LINE__ The line number on which it is written.
__FILE__ The full path and filename of the file in which it is written, with symlinks resolved.
__DIR__ The directory of the file, equivalent to dirname(__FILE__). It has no trailing slash unless it is the root directory.
__FUNCTION__ The name of the function in which it is written, including its namespace (e.g. Foo\bar). Inside a method, only the method name. For anonymous functions, a name generated by the engine that includes where the closure was defined (as of PHP 8.4.0; previously {closure}).
__CLASS__ The name of the class in which it is written, including its namespace (e.g. Foo\Bar). Inside a trait, the name of the class using the trait. For anonymous classes, a name generated by the engine. To get the name of the class a method was called on, use static::class.
__TRAIT__ The trait name, including its namespace (e.g. Foo\Bar).
__METHOD__ The class and method name of the method in which it is written (e.g. Foo\Bar::baz). Inside a trait, the trait name is used instead of the class name. Outside of a method, the same as __FUNCTION__.
__PROPERTY__ The name of the property, when used inside a property hook. Available as of PHP 8.4.0.
__NAMESPACE__ The name of the current namespace.

PHP's magic constants

Using magic constants

<?php
namespace App;

function helper()
{
    echo __FUNCTION__, "\n";
    echo __METHOD__, "\n";
}

trait Greets
{
    public function greet()
    {
        echo __CLASS__, "\n";
        echo __TRAIT__, "\n";
        echo __METHOD__, "\n";
        echo __FUNCTION__, "\n";
    }
}

class Greeter
{
    use Greets;
}

helper();
(new Greeter)->greet();
echo __NAMESPACE__, "\n";

    

ENTITY

App\helper
App\helper
App\Greeter
App\Greets
App\Greets::greet
greet
App

ENTITY

::class, get_class, get_called_class, dirname