4
In PHP, to check if a constant exists we use the function defined
. As below, for the two cases of constant declaration:
const MY_TEST_1 = 'my test 1';
define('MY_TEST_2', 'my test 2');
var_dump(defined('MY_TEST_1'), defined('MY_TEST_2')); // true, true
And when I declare a constante
in a namespace
or in a classe
? How do I verify their existence?
namespace StackOverflow {
const LANG = 'pt-br';
class StackOverflow
{
const MY_CONSTANT = 'minha constante';
}
}
From the above example, how would you verify the existence of StackOverflow\LANG
and StackOverflow\StackOverlow::MY_CONSTANT
?
If I wanted to check the constant that is outside the scope of namespace, I would have to do so
defined('\MY_CONSTANT')
?– Wallace Maxters
That. If you have a constant in the global namespace (
\\
) and you need to check it inside a namespace you use the bar.– gmsantos
Interesting! Works with
static
also!– Wallace Maxters
the part with
static
vi here.– gmsantos
Like the
static
works with the current class, so the guy defined the `defined('Static::CONST') within the abstract class. Very useful :)– Wallace Maxters