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

4
  • did you try $path = 'api\' . API_VERSION . '\service'; use $path; or use {'sdfsdf' . constant . 'sdfsdfsdf'} Commented Feb 22, 2018 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. Commented Feb 22, 2018 at 15:05
  • @Andrew read my previous comment. Commented Feb 22, 2018 at 15:05
  • if cant use constant, maybe can use static variable? Commented Feb 22, 2018 at 15:06

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Actually, your question is not a duplicate IMHO, because you are talking about the constants, not the variables.
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.
What stops you from using "use My\StaticConfig" and then just using the value of StaticConfig::VERSION whenever you want?
I've updated example. It might be more understandable.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.