Constants, in addition to being immutable, are global, that is, as long as the feature that depends on it is executed after its definition and is available (see below), just call it.
However, the most important thing is that despite its global scope, like everything that comes down to the Request flow, if the file where this constant was defined has not been included in the routine responsible for Normally, the constant, just like any other resource (variables, functions, classes ...) obviously will not exist.
There is also the namespaces issue raised while writing this response.
Constants are only defined in the context of a namespace if this is explicitly defined in the name of the constant. Ex:
<?php
namespace test;
define( 'FOO', 'BAR' );
define( 'test\NAMESPACED_CONSTANT', 'BAAZ' );
This code snippet will create two constants, but only the second will be restricted to the namespace test scope. So much so that this test:
var_dump( FOO, NAMESPACED_CONSTANT, test\NAMESPACED_CONSTANT );
Since error alerts are enabled and at a level sufficient to display a Notice , it will display a warning for assuming NAMESPACED_CONSTANT as a string, since it is not could be located in the constants defined .
Now, just to complement the subject ...
There are also Class Constants that almost of the same way as a regular constant, the difference is that they do not have global scope, being restricted only to the class (not the object) that they have defined (ram).
In addition, instead of the define () function, class constants are defined using the const keyword , especially within a class.
And to access them, use the self :: or parent :: pseudo-operators, depending on whether it was defined in the class that invoked it or in a superclass, respectively. If outside the scope of a class, the name of the defining class is used, respecting any declared namespaces :
class Foo {
const BAR = 'Baaz';
}
class MyClass {
public function __construct() {
echo Foo::BAR;
}
}
echo Foo::BAR; // Baaz
echo new MyClass; // Baaz
Finally, despite the name, Class Constants are not restricted to classes. These can also be defined in interfaces which widens the possibilities of typing offered by an interface.