0

I am trying to instantiate an object from a class, substituting an element from an array as the classname, but I keep getting PHP parse errors. I am thinking the \ character is somehow escaping the $ of the array varaiable? i.e.

$this->controller = new \app\controllers\$exploded_url[0];

gives

Parse error: syntax error, unexpected '$', expecting identifier (T_STRING)

$this->controller = new \app\controllers\${exploded_url[0]};

gives

Parse error: syntax error, unexpected '$exploded_url' (T_VARIABLE), expecting identifier (T_STRING)

How can I fix this parse error?

1 Answer 1

1

did you tried:

$temp = "\\app\\controllers\\".${exploded_url[0]};
$this->controller = new $temp;
Sign up to request clarification or add additional context in comments.

4 Comments

something is off in that syntax if I look at the syntax highlighting
but did you get idea? you can call new only from string.
yes, that does work, I thought is might have been possible without using a $temp placeholder. Also your closing string is probably going to be escaped by the backslash your syntax should be "\app\controllers\\"
namespaces in strings are just strings, meaning the backslash escapes the quote.

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.