PHP 8.5.2 Released!

define

(PHP 4, PHP 5, PHP 7, PHP 8)

defineDefine una constante

Descripción

define(string $constant_name, mixed $value, bool $case_insensitive = false): bool

Define una constante durante la ejecución.

Parámetros

constant_name

El nombre de la constante.

Nota:

Es posible definir con define() constantes con nombres reservados o incluso inválidos, donde sus valores pueden (solo) ser recuperados con la función constant(). Sin embargo, hacer esto no se recomienda.

value

El valor de la constante.

Advertencia

Aunque es técnicamente posible definir constantes de tipo resource, esto se desaconseja y puede causar comportamientos inesperados.

case_insensitive

Si es true, el nombre de la constante será insensible a mayúsculas/minúsculas: CONSTANT y Constant representan valores idénticos.

Advertencia

Definir constantes insensibles a mayúsculas/minúsculas está deprecado a partir de PHP 7.3.0. A partir de PHP 8.0.0, solo false es un valor aceptable, pasar true producirá una advertencia.

Nota:

Las constantes insensibles a mayúsculas/minúsculas se almacenan en minúsculas.

Valores devueltos

Esta función retorna true en caso de éxito o false si ocurre un error.

Historial de cambios

Versión Descripción
8.1.0 value ahora puede ser un objeto.
8.0.0 Pasar true a case_insensitive ahora emite una E_WARNING. Pasar false sigue siendo permitido.
7.3.0 case_insensitive está deprecado y será eliminado en la versión 8.0.0.

Ejemplos

Ejemplo #1 Definición de una constante

<?php
define
("CONSTANT", "Hola mundo.");
echo
CONSTANT; // muestra "Hola mundo."
echo Constant; // muestra "Constant" y emite una advertencia

define("GREETING", "Hola tú.", true);
echo
GREETING; // muestra "Hola tú."
echo Greeting; // muestra "Hola tú."

// Funciona desde PHP 7
define('ANIMALS', array(
'perro',
'gato',
'aves'
));
echo
ANIMALS[1]; // muestra "gato"

?>

Ejemplo #2 Constantes con Nombres Reservados

Este ejemplo ilustra la posibilidad de definir una constante con el mismo nombre que una constante mágica. Dado que el comportamiento resultante es confuso, esta práctica no se recomienda.

<?php
var_dump
(defined('__LINE__'));
var_dump(define('__LINE__', 'test'));
var_dump(constant('__LINE__'));
var_dump(__LINE__);
?>

El ejemplo anterior mostrará:

bool(false)
bool(true)
string(4) "test"
int(5)

Ver también

  • defined() - Verifica si una constante con el nombre dado existe
  • constant() - Retorna el valor de una constante
  • La sección sobre las constantes

add a note

User Contributed Notes 4 notes

up
100
ravenswd at gmail dot com
10 years ago
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.
up
29
@SimoEast on Twitter
8 years ago
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".)
up
29
danbettles at yahoo dot co dot uk
16 years ago
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!');
?>
up
4
eparkerii at carolina dot rr dot com
17 years ago
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.]
To Top