How to check if a defined constant exists in PHP?
So I'm using a PHP framework called fuelphp, and I have this page that is an HTML file, so I can't use PHP in it. I have another file that has a top bar in it, which my HTML file will call through ajax.
How do I check if a constant exists in PHP?
I want to check for the the fuelphp framework file locations.
These are the constants I need to check for (actually, I only have to check one of them):
define('DOCROOT', __DIR__.DIRECTORY_SEPARATOR);
define('APPPATH', realpath(__DIR__.'/fuel/app/').DIRECTORY_SEPARATOR);
define('PKGPATH', realpath(__DIR__.'/fuel/packages/').DIRECTORY_SEPARATOR);
define('COREPATH', realpath(__DIR__.'/fuel/core/').DIRECTORY_SEPARATOR);
require APPPATH.'bootstrap.php';
edit:
I realized that these aren't variables they are constants...
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.
Use defined()
function, for example:
if (defined('VAR_NAME')) {
// Something
}
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; } ?>
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