Reputation: 1085
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';
Upvotes: 92
Views: 128875
Reputation: 1877
With defined
you'll have to do something like that:
if (defined("CONST_NAME"))
$value = CONST_NAME;
This will work, but you'll could get an annoying error message in your code editor (in my case Visual Studio Code with PHP Inteliphense extension) for the second line, since it wont find CONST_NAME
.
Another alternative would be to use the constant function. It takes an string as the constant name and returns null if the constant is not defined:
$value = constant("CONST_NAME");
if ($value != null)
{
// Use the value ...
}
Since you passed the const name as a string, it wont generate an error on the code editor.
Upvotes: 1
Reputation: 1546
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
Upvotes: 33
Reputation: 25391
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; } ?>
Upvotes: 46
Reputation: 15616
Use defined()
function, for example:
if (defined('VAR_NAME')) {
// Something
}
Upvotes: 118
Reputation: 6786
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.
Upvotes: 107