Home » Php » In PHP 5 can I instantiate a class dynamically?

In PHP 5 can I instantiate a class dynamically?

Posted by: admin April 23, 2020 Leave a comment

Questions:

Is it possible to dynamically instantiate a class using a variable? For example is something like this possible in PHP?

class foo
{
    public $something;
}

$class_name = "foo";

$f = new $class_name();
How to&Answers:

That should work, yes.

You can also do:

$f = new $class($arg1,$arg2);

Answer:

Yes, this code will work fine.

Answer:

In PHP 5 can I instantiate a class
dynamically?

Yes you can, your code should work fine.

Answer:

Yes of course you can instantiate using dynamic names;