(PHP 4, PHP 5, PHP 7, PHP 8)
define — Определяет именованную константу
Функция определяет именованную константу во время выполнения кода.
constant_nameНазвание константы.
Замечание:
Функция define() умеет определять константы с названиями, которые совпадают с зарезервированными словами или даже нарушают правила языка по именованию идентификаторов, при этом значение таких констант вернёт только функция constant() , но делать так не рекомендуют.
valueЗначение константы.
Лучше не определять для констант значения с типом resource , хотя это и возможно, поскольку поведение таких констант непредсказуемо.
case_insensitive
Со значением true функция определит константу
без учёта регистра. По умолчанию названия констант чувствительны к регистру,
поэтому константы CONSTANT и Constant
представляют разные значения.
Начиная с PHP 7.3.0 определение нечувствительных к регистру констант
устарело.
Начиная с PHP 8.0.0 параметр принимает только значение false ,
передача true выдаст предупреждение.
Замечание:
Нечувствительные к регистру константы хранятся в нижнем регистре.
Функция возвращает true , если выполнилась успешно, или false , если возникла ошибка.
| Версия | Описание |
|---|---|
| 8.1.0 |
Параметр value теперь принимает объекты.
|
| 8.0.0 |
При передаче значения true в параметр case_insensitive теперь возникает ошибка уровня E_WARNING .
Передача значения false по-прежнему возможна.
|
| 7.3.0 |
Параметр case_insensitive устарел, а в версии 8.0.0 параметр удалят.
|
Пример #1 Определение констант
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // Выводит "Hello world."
echo Constant; // Выводит "Constant" и выдаёт уведомление
define("GREETING", "Hello you.", true);
echo GREETING; // Выводит "Hello you."
echo Greeting; // Выводит "Hello you."
// Начиная с PHP 7
define('ANIMALS', array(
'собака',
'кошка',
'птица'
));
echo ANIMALS[1]; // Выводит "кошка"
?>
Пример #2 Определение констант, названия которых совпадают с зарезервированными словами
Пример иллюстрирует доступность определения для константы названия, которое совпадает с названием магической константы. Лучше не давать константам такие названия, поскольку такое поведение явно сбивает с толку.
<?php
var_dump(defined('__LINE__'));
var_dump(define('__LINE__', 'test'));
var_dump(constant('__LINE__'));
var_dump(__LINE__);
?>Результат выполнения приведённого примера:
bool(false) bool(true) string(4) "test" int(5)
Be aware that if "Notice"-level error reporting is turned off, then trying to use a constant as a variable will result in it being interpreted as a string, if it has not been defined.
I was working on a program which included a config file which contained:
<?php
define('ENABLE_UPLOADS', true);
?>
Since I wanted to remove the ability for uploads, I changed the file to read:
<?php
//define('ENABLE_UPLOADS', true);
?>
However, to my surprise, the program was still allowing uploads. Digging deeper into the code, I discovered this:
<?php
if ( ENABLE_UPLOADS ):
?>
Since 'ENABLE_UPLOADS' was not defined as a constant, PHP was interpreting its use as a string constant, which of course evaluates as True.Not sure why the docs omit this, but when attempting to define() a constant that has already been defined, it will fail, trigger an E_NOTICE and the constant's value will remain as it was originally defined (with the new value ignored).
(Guess that's why they're called "constants".)define() will define constants exactly as specified. So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace. The following examples will make it clear.
The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").
<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>
The following code will define two constants in the "test" namespace.
<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>Found something interesting. The following define:
<?php
define("THIS-IS-A-TEST","This is a test");
echo THIS-IS-A-TEST;
?>
Will return a '0'.
Whereas this:
<?php
define("THIS_IS_A_TEST","This is a test");
echo THIS_IS_A_TEST;
?>
Will return 'This is a test'.
This may be common knowledge but I only found out a few minutes ago.
[EDIT BY danbrown AT php DOT net: The original poster is referring to the hyphens versus underscores. Hyphens do not work in defines or variables, which is expected behavior.]