0

Is it possible to use variable in use statement? How to implement version control with traits and other files i define with use statement?

<?php
namespace SomeNamespace;

$vers = '10'; 

use SomeNamespace2\someTrait_$vers;
use SomeNamespace3\someTrait_$vers;

I would like to be able to assign single version to all use statements.

olga
  • 959
  • 1
  • 15
  • 42
  • There's no language support for that. Investigate build or preprocessing tools. (After you made sure this use case is really worth the effort.) – mario Nov 16 '18 at 23:47

2 Answers2

2

@Nick's answer is a good option. But class_alias might be a better fit. (Or worse, depending on your situation or preferences...) Something like:

class_alias("SomeNamespace2\\someTrait_$vers", 'SomeNamespace2\someTrait');

and then just reference SomeNamespace2\someTrait in the rest of your code.

Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
  • I just had to try this out since I'd never heard of the `class_alias` function before. But it actually does work: https://3v4l.org/X93UR – rickdenhaan Nov 17 '18 at 01:07
  • I came across it in the source for CakePHP. They are using it to provide aliases to old, deprecated class names from the new names. Very similar under the hood to the "use X as Y" method, except that as a function it can take variables in the arguments. – Greg Schmidt Nov 17 '18 at 01:11
  • That is cool. I'd not encountered it before either. Always love to learn something new. – Nick Nov 17 '18 at 02:16
0

Although PHP has no support for variables in use statements, you could overcome that by putting your use statements (and other version specific code) into a series of include files (one for each version) and then use a variable in a require (or include) statement to include the file you want. For example:

use_10.php:

use SomeNamespace2\someTrait_10;
use SomeNamespace3\someTrait_10;

use_11.php:

use SomeNamespace2\someTrait_11;
use SomeNamespace3\someTrait_11;

Your main PHP code:

$vers = 10;   // or 11, or any value for which you have created an include file
require_once "use_$vers.php";
Nick
  • 138,499
  • 22
  • 57
  • 95