Php define and use
Задумывались ли вы кода-нибудь — смотришь на синтаксис и видишь фигу. (интерпретация «смотришь в книгу видишь фигу»)
Для этого и существует наш сайт, чтобы эти фиги не вылазили!
На не раскрашенные строки, можно даже не смотреть!
case_insensitive — зависимость от регистра.
Как работает define();
Имя константы задаётся параметром name;
Значение константы определяется параметром value.
Если case_insensitive используется как TRUE, то регистр отключен.
Примеры использования define/константы в php
Давайте разберем пример использования и вывода константы:
Выведем ранее заданную константу через echo:
Результат вывода значения константы:
Далее. попробуем изменить значение константы:
Выведем тут же через echo:
Как видим, значение нашей константы не изменилось, что собственно мы и хотели показать!
Ошибки констант в php
Notice: Constant already defined
Если при таком алгоритме создании константы, то выведет ошибку «Notice: Constant already defined»(если вывод данной ошибки включен) и результат echo «val».
define(‘FOO’, ‘val2’); // Notice: Constant already defined
Невозможно задать массив в константе
Невозможно задать массив в константе до PHP 7.0 — возникнет ошибка типа «Warning»
define( ‘FOO’, array(1) ); // Warning: Constants may only evaluate to scalar values in page.html on line №
define
Note:
It is possible to define() constants with reserved or even invalid names, whose value can (only) be retrieved with constant() . However, doing so is not recommended.
The value of the constant. In PHP 5, value must be a scalar value ( int , float , string , bool , or null ). In PHP 7, array values are also accepted.
While it is possible to define resource constants, it is not recommended and may cause unpredictable behavior.
If set to true , the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. CONSTANT and Constant represent different values.
Defining case-insensitive constants is deprecated as of PHP 7.3.0. As of PHP 8.0.0, only false is an acceptable value, passing true will produce a warning.
Note:
Case-insensitive constants are stored as lower-case.
Return Values
Returns true on success or false on failure.
Changelog
Version | Description |
---|---|
8.0.0 | Passing true to case_insensitive now emits an E_WARNING . Passing false is still allowed. |
7.3.0 | case_insensitive has been deprecated and will be removed in version 8.0.0. |
7.0.0 | array values are allowed. |
Examples
Example #1 Defining Constants
define ( «CONSTANT» , «Hello world.» );
echo CONSTANT ; // outputs «Hello world.»
echo Constant ; // outputs «Constant» and issues a notice.
?php
define ( «GREETING» , «Hello you.» , true );
echo GREETING ; // outputs «Hello you.»
echo Greeting ; // outputs «Hello you.»
// Works as of PHP 7
define ( ‘ANIMALS’ , array(
‘dog’ ,
‘cat’ ,
‘bird’
));
echo ANIMALS [ 1 ]; // outputs «cat»
Example #2 Constants with Reserved Names
This example illustrates the possibility to define a constant with the same name as a magic constant. Since the resulting behavior is obviously confusing, it is not recommended to do this in practise, though.
var_dump ( defined ( ‘__LINE__’ ));
var_dump ( define ( ‘__LINE__’ , ‘test’ ));
var_dump ( constant ( ‘__LINE__’ ));
var_dump ( __LINE__ );
?>?php
The above example will output:
bool(false) bool(true) string(4) "test" int(5)
See Also
- defined() — Checks whether a given named constant exists
- constant() — Returns the value of a constant
- The section on Constants
User Contributed Notes 17 notes
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:
define ( ‘ENABLE_UPLOADS’ , true );
?>
Since I wanted to remove the ability for uploads, I changed the file to read:
//define(‘ENABLE_UPLOADS’, true);
?>
However, to my surprise, the program was still allowing uploads. Digging deeper into the code, I discovered this:
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»).
namespace test ;
define ( ‘MESSAGE’ , ‘Hello world!’ );
?>
The following code will define two constants in the «test» namespace.
namespace test ;
define ( ‘test\HELLO’ , ‘Hello world!’ );
define ( __NAMESPACE__ . ‘\GOODBYE’ , ‘Goodbye cruel world!’ );
?>
With php 7 you can now define arrays.
consider the following code:
define ( «EXPLENATIVES» , [ 1 => «Foo Bar» , 2 => «Fehw Bahr» , 3 => «Foo Bahr» , 4 => «Fooh Bar» , 5 => «Fooh Bhar» , 6 => «Foo Barr» , 7 => «Foogh Bar» , 8 => «Fehw Barr» , 9 => «Fu bar» , 10 => «Foo Bahr» , 11 => «Phoo Bar» , 12 => «Foo Bawr» , 13 => «Phooh Baughr» , 14 => «Foogan Bargan» , 15 => «Foo Bahre» , 16 => «Fu Bahar» , 17 => «Fugh Bar» , 18 => «Phou Baughr» ]);
//set up define methods using mixed values; both array and non-array values
define ( «NAVBTNS» , [ EXPLENATIVES , «Nouns» , «Verbs» , «Adjectives» ]);
//function to create a dropdown menu using the EXPLENATIVES array $btn=EXPLENATIVES=assoc_array
Love this new implementation !
The value of a constant can be the value of another constant.
define ( «NEW_GOOD_NAME_CONSTANT» , «I have a value» );
define ( «OLD_BAD_NAME_CONSTANT» , NEW_GOOD_NAME_CONSTANT );
echo NEW_GOOD_NAME_CONSTANT ; // current
echo OLD_BAD_NAME_CONSTANT ; // legacy
This is obvious, but easy to forget: if you include a file, the include file can only make use of constants already defined. For example:
define ( «VEG» , «cabbage» );
require( «another file» );
define ( «FRUIT» , «apple» );
// «another file»:
echo VEG ; // cabbage
echo FRUIT ; // FRUIT
?>
Since version 8 or 8.1, beat me if I recall any type of class
as defined constant value is perfectly valid.
Should You use it, I wouldn’t know.
Most probably, referencing with such instances will fail badly.
But it might come handy for public and readonly classes.
define ( ‘ClassInstance’ ,
new class extends \ My \ OtherClass
private bool $toggle = false ;
private float $real = 1.2345 ;
private ? string $obj = null ;
public function __construct () $this -> privatemethod ();
>
private function privatemethod () $this -> obj = var_export ( $this , true );
>
Found something interesting. The following define:
define ( «THIS-IS-A-TEST» , «This is a test» );
echo THIS — IS — A — TEST ;
?>
Will return a ‘0’.
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.]You can define constants with variable names (works also with constant values or variables or array values or class properties and so on — as long it’s a valid constant name).
# Define a constant and set a valid constant name as string value
define ( «SOME_CONSTANT» , «NEW_CONSTANT» );
# Define a second constant with dynamic name (the value from SOME_CONSTANT)
define ( SOME_CONSTANT , «Some value» );
# Output
echo SOME_CONSTANT ; // prints «NEW_CONSTANT»
echo «
» ;
echo NEW_CONSTANT ; // prints «Some value»
?>
Needless to say that you’ll lose your IDE support for refactoring and highlighting completely for such cases.
No clue why someone would / could actually use this but i thought it’s worth mentioning.
Php 7 — Define: «Defines a named constant at runtime. In PHP 7, array values are also accepted.»
But prior PHP 7, you can maybe do this, to pass an array elsewhere using define:
$to_define_array = serialize($array);
define( «DEFINEANARRAY», $to_define_array );
$serialized = DEFINEANARRAY; // passing directly the defined will not work
$our_array = unserialize($serialized);
I think worth mentioning is that define() appears to ignore invalid constant names.
One immediate implication of this seem to be that if you use an invalid constant name you have to use constant() to access it and obviously that you can’t use the return value from define() to tell you whether the constant name used is invalid or not.
For example:
$name = ‘7(/!§%’;
var_dump(define($name, «hello»)); // outputs bool(true)
var_dump(constant($name)); // outputs string(5) «hello»
There’s an undocumented side-effect of setting the third parameter to true (case-insensitive constants): these constants can actually be «redefined» as case-sensitive, unless it’s all lowercase (which you shouldn’t define anyway).
The fact is that case-sensitive constants are stored as is, while case-insensitive constants are stored in lowercase, internally. You’re still allowed to define other constants with the same name but capitalized differently (except for all lowercase).
// «echo CONST» prints 1, same as «echo const», «echo CoNst», etc.
define ( ‘CONST’ , 1 , true );
echo CONST; // Prints 1
define ( ‘CONST’ , 2 );
echo CONST; // Prints 2
echo CoNsT; // Prints 1
echo const; // Prints 1
// ** PHP NOTICE: Constant const already defined **
define ( ‘const’ , 3 );
echo const; // Prints 1
echo CONST; // Prints 2
?>
Why would you use this?
A third party plugin might attempt to define a constant for which you already set a value. If it’s fine for them to set the new value, assuming you cannot edit the plugin, you could define your constant case-insensitive. You can still access the original value, if needed, by using any capitalization other than the one the plugin uses. As a matter of fact, I can’t think of another case where you would want a case-insensitive constant.
For translating with variables and define, take also a look on the constant() function.
define ( ‘PAYMENT_IDEAL’ , «iDEAL Payment ( NL only )» );
define ( ‘PAYMENT_MASTERCARD’ , «Mastercard Payment ( international )» );
echo constant ( «PAYMENT_ $payparam » );
// output :
// Mastercard Payment ( international )
?>
To clear up a few thing:
Integers with 0 in front work. But since PHP (and many other languages) handle them as octal values, they’re only allowed a range of 0-7:
define ( ‘GOOD_OCTAL’ , 0700 );
define ( ‘BAD_OCTAL’ , 0800);
print GOOD_OCTAL ;
print ‘
‘ ;
print BAD_OCTAL ;
?>
Result:
448
0
writing the constant name without the quotation-marks (as mentioned in the notes) throws an E_NOTICE and should be avoided!
define ( TEST , ‘Throws an E_NOTICE’ );
?>
Result:
Notice: Use of undefined constant TEST — assumed ‘TEST’
It may be worth stating that a define function must be executed before its global constant is referenced.
Abc();
define(«TEST», 23);
function Abc()
echo TEST;
> // Abc
This code fails with a Notice-level message. TEST is treated here as being the string «TEST».
A namespace constant can be defined using the define function, the constant defined this way is not global.
namespace WuXiancheng ;
\ define ( ‘China\Sichuan\Guangan\Yuechi\ZIP’ , 638300 );
echo ZIP ; //Use of undefined constant ZIP
echo \ China \ Sichuan \ Guangan \ Yuechi \ ZIP ; // 638300
?>
If you happen to name your constant the same as a function name (either a built-in function or a user-defined one), PHP can handle this correctly based on context. For example:
function myfunc () return ‘function output’ ;
>
define ( ‘MYFUNC’ , ‘constant value’ );
// note that function names are NOT case-sensitive
// so calling MYFUNC() is the same as calling myfunc()
echo ‘MYFUNC(): ‘ . MYFUNC () . ‘, MYFUNC: ‘ . MYFUNC ;
?>
Output:
MYFUNC(): function output, MYFUNC: constant value
- Misc. Functions
- connection_aborted
- connection_status
- constant
- define
- defined
- die
- eval
- exit
- get_browser
- __halt_compiler
- highlight_file
- highlight_string
- hrtime
- ignore_user_abort
- pack
- php_strip_whitespace
- sapi_windows_cp_conv
- sapi_windows_cp_get
- sapi_windows_cp_is_utf8
- sapi_windows_cp_set
- sapi_windows_generate_ctrl_event
- sapi_windows_set_ctrl_handler
- sapi_windows_vt100_support
- show_source
- sleep
- sys_getloadavg
- time_nanosleep
- time_sleep_until
- uniqid
- unpack
- usleep