3

I tried the code below:

$dyn = "new ". $className . "(" .$param1 . ", ". $param2 . ");";
$obj = eval($dyn);

It compiles but it's null.

How can you instance object in PHP dynamicaly?

3 Answers 3

19
$class = 'ClassName';
$obj = new $class($arg1, $arg2);
Sign up to request clarification or add additional context in comments.

3 Comments

what if class name in static property? class From { static $toCreate='ClassName';}
I believe doing new From::$toCreate() should still work... If not then you would just assign it to var before instantiation.
its not exactly what I meant. We have class class From { static $toCreate='ClassName'; public static function some(){};}. We need to call static method some, and it should have syntax like Form::$toCreate::some(). Ofcourse, it wouldnt work. But we can like $dynName=Form::$toCreate; $dynName::some() and it will work. But this is not much perfect (
4

If you really want to use eval - which chances are you shouldn't if you're this new to PHP ;) - you'd do something more like...

$dyn = "new ". $className . "(" .$param1 . ", ". $param2 . ");";
eval("\$obj = $dyn");

1 Comment

Just because someone is starting to learn a language, it doesn't necessarily mean they have no experience programming.. but it's a fair warning for new developers :)=
1

What are you actually trying to accomplish? eval would work, but its probably not a very good idea.

What you might want to do is implement a factory for your objects that take a string defining what class to load, and an optional array for the constructors parameters

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.