php, version control and use statements

42 views Asked by At

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.

2

There are 2 answers

0
Nick On

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";
3
Greg Schmidt On

@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.