从名称空间中的变量名称实例化新类
问题描述:
比方说,我有一个类:
//no namespace
class User {
//...
}
我有一个变量:
$model = 'User';
当我当前在命名空间中时,如何实例化new User
?
How do I instantiate a new User
when I am currently in a namespace?
new $model
可以工作.但是,如果我在名称空间中而User
不在名称空间中,该怎么办.
new $model
works when I'm not in a namespace. But what if I am in a namespace and User
is not in a namespace.
类似的事情不起作用:
namespace Admin;
class Foo {
function fighter($model)
{
return new \$model;
// syntax error, unexpected '$model'
}
}
}
答
首先将完整的命名空间放入变量中,然后使用它.
Put the complete Namespace first in a variable and then use it.
<?php
$namespace = '\\'.$model;
return new $namespace
?>
相同主题: PHP名称空间可以包含变量吗?