In PHP 5 can I instantiate a class dynamically?

2019-02-16 04:02发布

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();

4条回答
欢心
2楼-- · 2019-02-16 04:20

That should work, yes.

You can also do:

$f = new $class($arg1,$arg2);
查看更多
太酷不给撩
3楼-- · 2019-02-16 04:23

In PHP 5 can I instantiate a class dynamically?

Yes you can, your code should work fine.

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-16 04:37

Yes of course you can instantiate using dynamic names;

查看更多
走好不送
5楼-- · 2019-02-16 04:38

Yes, this code will work fine.

查看更多
登录 后发表回答