James
James

Reputation: 4783

Different ways to define a constant in a namespace

There seems to be different ways to put constants in a namespace, and selected ways to display them depending on how they are defined.

Brief Overview:
If I define a constant and use namespace user; I cannot use \user\CONSTANT to later access it.
If define a constant with the namespace name, e.g. define('user\USERNAME', 'James'), I don't need to use namespace user; and can access the constant in two ways - using the namespace user; and user\USERNAME.

EXAMPLES:

Note:
All examples include the entire code used in the test file (if code from a previous example is missing it's because it wasn't used in the new test)

define.php

namespace user;
define('USERNAME', 'James');
include 'display.php';

display.php

namespace user;
echo USERNAME; // Displays "James"

// This will NOT work (Fatal error: Undefined constant)
echo \user\USERNAME;

However I can set the constant in the namespace another way:
define.php

define('user\USERNAME', 'James');
include 'display.php';

And now I have TWO ways to display the constant:

display.php

namespace user;
echo USERNAME; // Displays "James"

AND

display.php

echo \user\USERNAME; // Displays "James"

Both display "James" just fine.

My Question

I'm not asking what you prefer etc, but is there a problem with using either of these methods?
Is one better due to performance (presume micro secs so pointless), or perhaps does one method cause issues somewhere else in PHP?

I know not explicitly setting the namespace like namespace user; means I don't get anything else in that file set to the namespace, which would be ok if I only want constant(s) in the namespace.

Is this simply a choice depending on scenario, or is one method bad for some reason?

Upvotes: 3

Views: 958

Answers (1)

hexerei software
hexerei software

Reputation: 3160

You should use the second variant, if you want to define the constant in the namespace only. so

define('user\USERNAME', 'James');

is not just the preferred syntax, it is the only correct syntax. if you are writing

define('USERNAME', 'James');

then you are defining a GLOBAL CONST even if your define call is done within the user namespace. So obviously this would work, because you can access the value from within the namespace - but also from within any namespace, so not what you wanted :)

Upvotes: 2

Related Questions