Search code examples
phpclassnamespacesusing

Use variable as namespace


In some other file (someusername\classes\MyClass for instance), I have

<?php
namespace someusername;
class MyClass
{
  static function Test()
  {
    echo "working";
  }
}
?>

I have stumbled across an annoying little barrier:

<?php

$user = "someusername";
$class = "MyClass";

require_once "$user\\classes\\$class";

//This line should be the equivalent of 'use someusername as User;'
use $user as User; //Parse Error: syntax error, unexpected '$user' 

$c = "User\\$class";
$UserSpecificClass = new $c();
?>

I can get around it via the following, but the use statement would make things a lot nicer

<?php

$user = "someusername";
$class = "MyClass";

require_once "$user\\classes\\$class";

$c = "$user\\$class";

$UserSpecificClass = new $c();
?>

Is it possible to use variables in use statement in PHP? Or is it better to avoid the use statement with this approach?


Solution

  • Importing is performed at compile-time.

    Assigning the variable is done at run-time after compilation, at which point any import should already be imported.

    So this is not possible. Best solution would indeed be to use the FQN in a string and initialize that.

    $c = "$user\\$class";
    
    $UserSpecificClass = new $c();