1

I've searched a lot of other similar Q/As but none of them seem to address this specific case:

There's a file with constants: App/Core/SomeConstants.php which contains:

namespace App\Core\SomeConstants;
const MY_CONST = 'myconstvalue';

Then there's a controller using this constant like so:

use const App\Core\SomeConstants\MY_CONST;
something("foo" . MY_CONST);

According to https://www.php.net/manual/en/language.namespaces.importing.php this I thought would work, but doesn't and when I run that usage code (of course after reloading the autoloader/clearing cache), I get Undefined constant \"App\\Core\\SomeConstants\\MY_CONST\"".

I even tried full-namespace referencing like something("foo" . \App\Core\SomeConstants\MY_CONST); and still nothing.

What's also interesting is that IDE vscode doesn't have an issue with it and actually shows proper hinting and stuff in both of the cases.

What am I doing wrong? Can it even be done without wrapping the constant into a class? Where is this behavior documented? Thanks

jave.web
  • 13,880
  • 12
  • 91
  • 125
  • I tested your example and it works. Constant defined in one namespace and used in other, same as in your post. That said - I would still consider putting it into some class. – Andis Jun 16 '22 at 17:53
  • 2
    You are missing the `require` directive. AFAIK, composer won't autoload them automatically. See [this answer](https://stackoverflow.com/q/17404351/#17404435) for the required configuration. – msg Jun 16 '22 at 22:42
  • @msg that is very sad, but using the ` "files"` section in `autoload` section of `composer.json` worked, so at least there's a bypass :-) thank you – jave.web Jun 17 '22 at 08:12

0 Answers0