PHP 8.5.2 Released!

define

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

defineDefine uma constante com nome

Descrição

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

Define uma constante com nome em tempo de execução.

Parâmetros

constant_name

O nome da constante.

Nota:

É possível definir constante pela função define() com nome reservado ou até mesmo com nome inválido, cujo valor pode (somente) ser recuperado com a função constant(). Entretanto, isto não é recomendado.

value

O valor da constante.

Aviso

Apesar de ser possível definir constantes do tipo resource, não é recomendado e pode causar comportamento imprevisível.

case_insensitive

Se definido para true, a constante será definida sem diferenciação de maiúsculas/minúsculas. O comportamento padrão é diferenciar, isto é, CONSTANT e Constant representam valores diferentes.

Aviso

Definir constantes sem diferenciar maiúsculas/minúsculas foi descontinuado a partir do PHP 7.3.0. A partir do PHP 8.0.0, somente false é um valor aceitável para este parâmetro, passar true irá gerar um alerta.

Nota:

Constantes insensíveis a maiúsculas/minúsculas são armazenadas em minúsculas.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Registro de Alterações

Versão Descrição
8.1.0 value agora pode ser um objeto.
8.0.0 Passar true para case_insensitive agora emite um E_WARNING. Passar false ainda é permitido.
7.3.0 case_insensitive foi descontinuado e será removido na versão 8.0.0.

Exemplos

Exemplo #1 Definindo Constantes

<?php
define
("CONSTANTE", "Olá, mundo.");
echo
CONSTANTE; // exibe "Olá, mundo."
echo Constante; // exibe "Constante" e emite um aviso.

define("CUMPRIMENTO", "Tudo bem?", true);
echo
CUMPRIMENTO; // exibe "Tudo bem?"
echo Cumprimento; // exibe "Tudo bem?"

// Funciona a partir do PHP 7
define('ANIMAIS', array(
'cachorro',
'gato',
'pássaro'
));
echo
ANIMAIS[1]; // exibe "gato"

?>

Exemplo #2 Constantes com Nomes Reservados

Este exemplo ilustra a possibilidade de definir uma constante com o mesmo nome de uma constante mágica. Como o comportamento resultante obviamente é confuso, não é portanto recomendado fazê-lo na prática.

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

O exemplo acima produzirá:

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

Veja Também

adicionar nota

Notas de Usuários 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