4

Possible Duplicate:
PHP namespace with Dynamic class name

How to declare class from string?

code

$name = 'the_class';
require_once $name.'.php';
$class = new \resource\$name();

error

Parse error: syntax error, unexpected '$name' (T_VARIABLE), expecting identifier (T_STRING)
5
  • @WesleyMurch: That's incorrect. See some of the answers below for how to do this properly. Commented Nov 10, 2012 at 20:11
  • @drrcknlsn: That's fantastic, although very ugly. I'm still amazed that chosen syntax for namespaces was backslash, which is pretty much universally an escape character. Commented Nov 10, 2012 at 20:12
  • @Wesley Murch, it was one of the only unused characters available for syntax. Commented Nov 10, 2012 at 20:15
  • @JasonMcCreary: ★resource★classname() would be much cooler. Commented Nov 10, 2012 at 20:16
  • It's too bad that other characters couldn't be used, and have the interpreter simply recognize the context in which it was used. For example why would $class = new Resource.Classname(); be an issue unless it was a shortcoming of the compiler? There's no ambiguity because the . could never work for concatenation in that context (right?). Just some thoughts - I'm sure there's a reason, it's really over my head, and I've gotten used to the backslash and almost like it now. Commented Nov 10, 2012 at 20:20

2 Answers 2

7

You will need to dynamically construct the namespace path:

$classPath = '\\resource\\' . $name;
$class = new $classPath;

Note: I like to be explicit with literal backslashes.

Sign up to request clarification or add additional context in comments.

Comments

4

The namespace needs to be part of the string:

$name = 'the_class';
require_once $name . '.php';
$className = '\resource\\' . $name;
$class = new $className();

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.