How to check if a constant exists in PHP

二次信任 提交于 2019-11-30 07:48:38
Eric MORAND

First, these are not variables, but constants.

And you can check their existence by using the defined() function :

bool defined ( string $name )

Checks whether the given constant exists and is defined.

Tom Walters

Use defined() function, for example:

if (defined('VAR_NAME')) {
    // Something
}
Niklas

Check using defined('CONSTANT') function.

An example from the manual:

<?php
/* Note the use of quotes, this is important.  This example is checking
 * if the string 'TEST' is the name of a constant named TEST */
if (defined('TEST')) {
    echo TEST;
}
?>
Svetoslav Marinov

here's a cooler & more concise way to do it:

defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');

credit: daniel at neville dot tk https://www.php.net/manual/en/function.defined.php#84439

I take it you mean CONSTANTS not variables! the function is defined();

see here: defined

i use this method:

if (defined('My_variable') && (DEFAULT_LANGUAGE != '') && (DEFAULT_LANGUAGE != 'My_variable') )
{
  // your codes here
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!