1

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?

1
  • What is the point of use if it's not to shorten or rename namespace+class and make the code clearer? Your code will never be clear and you can just keep the whole namespace+class in a variable anyway. Commented Dec 15, 2014 at 20:58

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.