1

I'm trying to use a constant in a PHP Namespace Use statement:

define('API_VERSION', 'v201705');

I'd like to be able to use the constant above in the use statement below

use api\v201705\service;

I don't know if this is possible as the following obviously does't work:

use api\.API_VERSION.\service;

Can anyone suggest a different approach to using a constant in this scenario?

Any help would be appreciated.

Thanks

Boomfelled
  • 515
  • 5
  • 14
  • did you try $path = 'api\' . API_VERSION . '\service'; use $path; or use {'sdfsdf' . constant . 'sdfsdfsdf'} – Andrew Feb 22 '18 at 15:04
  • PHP namespaces are evaluated on the compilation. The constant is defined and used during the runtime (that happens after the compilation step and only if the compilation succeeded). It doesn't work as you want. – axiac Feb 22 '18 at 15:05
  • @Andrew read my previous comment. – axiac Feb 22 '18 at 15:05
  • if cant use constant, maybe can use static variable? – Andrew Feb 22 '18 at 15:06

1 Answers1

1

The workaround I would use here is a just usage of class constants.

Then

  1. You don't need to override your autoloader
  2. You can group constants semantically
  3. "define" has global visibility, you don't need it in 99% of use cases.
  4. You don't need to instantiate class in order to use class constants. Thus it's quite cheap operation.

namespace My;

class StaticConfig {  
   const VERSION = '1.2.3';
}

...        
use My\StaticConfig;
echo StaticConfig::VERSION;

Actually, it's even not a workaround, it's quite common practice.

Alex
  • 4,621
  • 1
  • 20
  • 30
  • 1
    Actually, your question is not a duplicate IMHO, because you are talking about the constants, not the variables. – Alex Feb 22 '18 at 15:54
  • Thanks very much Alex, the only trouble with your answer is that I can't use My\StaticConfig::VERSION; within a use statement, like this: use My\StaticConfig::VERSION; Thanks again. – Boomfelled Feb 22 '18 at 16:30
  • What stops you from using "use My\StaticConfig" and then just using the value of StaticConfig::VERSION whenever you want? – Alex Feb 22 '18 at 16:36
  • I've updated example. It might be more understandable. – Alex Feb 22 '18 at 16:43
  • Thanks very much Alex, but I just don't understand enough PHP to get your example working. Thanks again for your help, what I have in place works, it's not ideal but I'll stick with it. – Boomfelled Feb 22 '18 at 16:49