Constants, in addition to immutable are global, that is, as long as the resource that depends on it is executed after its definition and is available (see below), just call for it.
However, the most important thing is that despite its global scope, like everything that comes down to the Request flow, in case the file where this constant was defined has not been included in the routine responsible for the current Request, it, the constant, as well as any other resource (variables, functions, classes...) will obviously not exist.
There is also the question of namespaces, raised while writing this reply.
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 fragment will create two constants, but only the second will be restricted to the scope of the namespace test. So true that this test:
var_dump( FOO, NAMESPACED_CONSTANT, test\NAMESPACED_CONSTANT );
Whereas error alerts are enabled and at a sufficient level to display a Notice, It will display a warning to assume NAMESPACED_CONSTANT as a string, since it could not be located in the middle of the defined constants.
Now, just as a complement to the subject...
There are still the Class constants working almost in the same way as a regular constant, the difference is that they have not global scope, being restricted only to the class (not to the object) that a(s) defined (ram).
Also, instead of the function defines(), class constants are defined by keyword const, special within a class.
And to access them, pseudo-operators are used self:: or Parent::, 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 namespaces declared:
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 extends the typing possibilities offered by an interface.
You realize your constant is called
FOO
, but you’re trying to use asFoo
?– bfavaretto
The inverted quotation mark at the end of the
define
is a typo?– gmsantos
Probable, as well as the double asterisks within the code block.
– Bruno Augusto
Actually I put the double asterisks to visualize better where I wanted to print the constant and the 'Foo' with lowercase letter was my lack of attention when typing
– BackFront
All right, but then, did you? If yes, mark the answer that helped you as resolved. Your doubt today may be that of another tomorrow. ;)
– Bruno Augusto