New object with name in variable
Clash Royale CLAN TAG#URR8PPP
New object with name in variable
I am trying to initiate an object with a dynamic path. I have the variable $model
with the model name.
$model
$model = "foo";
$class = new PathTo$model();
I get the error
Parse error: syntax error, unexpected '$model' (T_VARIABLE), expecting identifier (T_STRING)
If I try $class = new PathTo$model();
I get the error
$class = new PathTo$model();
Parse error: syntax error, unexpected '{', expecting identifier (T_STRING)
When I try
namespace AppModels
$class = new $model();
I get the error Class 'foo' not found
Class 'foo' not found
When I try $class = new PathTofoo();
it works.
$class = new PathTofoo();
Any ideas?
2 Answers
2
Try:
$class = "PathTofoo";
$object = new $class();
Or:
use PathTofoo;
$class = foo::class;
$object = new $class();
You can store path in variable:
$path = "PathTo\";
and then generate class name like this:
$className = $path.$model;
$class = new $className();
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.