0

I just got stuck with the following problem. I'm trying to construct a class but it isn't working. When I'm constructing the class it uses namespaces and variables, because the variable has to be put behind a backslash (for the namespace) it gives an error. Here's an example code of defining the class;

$className = 'Help';
$controller = new \controller\$className;

The class name is defined in a variable, in the example code above I've just set it to 'Help'. When constructing the class it has \controller\ in front of it, that's cause it's in that namespace. If I remove the namespace thing away so it just has;

$controller = new $className;

it does work. The problem is probably caused because there's a backslash in front of the variable which contains the class name to construct. I am not able to add use controller; in the beginning of the code because the file containing the class is loaded inside the constructor, and the class is immediately constructed after the file has been loaded. The use function could only be used in the beginning of your file, not inside a method, I think.

I hope someone could help me out,.

Thanks in advance, Tim Visée

2 Answers 2

3

Your first example is invalid syntax. You would need instead something like:

$className = '\controller\Help';
$controller = new $className();
Sign up to request clarification or add additional context in comments.

Comments

3

Set the fully qualified class name to a variable and use that to instantiate a new object:

$className = '\controller\Help';
$controller = new $className;

Comments

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.