3

Would it be possible to import namespaces using a variable like this:

$namespace = 'User\Authorization\Certificate';
use $namespace;

Obviously this won't run as use statement expects a constant but is there a workaround?

Edit: Discovered a gem (only in PHP > 5.3): class_alias($namespace, alias); which does pretty much the same thing with use User\Authorization\Certificate as alias; so will be using that.

3
  • 1
    I wonder what you're trying to achieve. Commented Jun 19, 2011 at 19:32
  • Well I'm combining the require_once & use statements into an import(..) function with the help of very structured class and folder hierarchy. Commented Jun 19, 2011 at 20:17
  • Is it considerable to modify the content of the files you require on the fly to introduce your namespace? Commented Jun 19, 2011 at 21:00

2 Answers 2

2

While it isn't possible to pass a namespace in a variable to use, you can place the namespace and the expected "short" class name in a variable and use that in most places where you'd need it, like invoking new.

$namespace = '\foo\bar';
$class = 'baz';
$fully_qualified = $namespace . '\\'. $class; // \foo\bar\baz
$a_foo_bar_baz = new $fully_qualified(...);
var_dump( $a_foo_bar_baz instanceof $fully_qualified ); // true
Sign up to request clarification or add additional context in comments.

1 Comment

I went with class_alias(..) function which is pretty much what you're trying to achieve in the code so nice solution.
0

No, PHP expects the use to follow a namespace, not an expression (which includes not a constant). See Using namespaces: Aliasing/Importing.

However if you change the PHP code on the fly before executing it in some kind of aggregation or compilation phase within your system, you could replace the text with some variable data which looks static enough for PHP then.

But I have no idea if your system is capable of doing so. I could imagine some stream wrapper or stream filter doing this on the fly. It could transparently take care of inserting the variable namespace name.

4 Comments

changing .php files on the fly, can result in it being truncated to 0 bytes if accessed simultaneously by more than one user, or something like that... i remember having terrible experience with my .txt "databases" vanishing back when php+mysql hosting was so rare that you had to pay for it.
I don't think that this applies. If so, it would be a problem for the bare require/include already. Changing on the file does not need to actually save the file again btw.
you meant loading the .php, changing the text and then using eval()?
No need for eval, require can be used. See stream wrapper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.