问题
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...
回答1:
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.
回答2:
Use defined() function, for example:
if (defined('VAR_NAME')) {
// Something
}
回答3:
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; } ?>
回答4:
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
回答5:
I take it you mean CONSTANTS not variables! the function is defined();
see here: defined
回答6:
i use this method:
if (defined('My_variable') && (DEFAULT_LANGUAGE != '') && (DEFAULT_LANGUAGE != 'My_variable') )
{
// your codes here
}
来源:https://stackoverflow.com/questions/14429321/how-to-check-if-a-constant-exists-in-php