【问题标题】:Instantiate a new class from a variable's name in a namespace从命名空间中的变量名实例化一个新类
【发布时间】:2012-08-08 22:49:14
【问题描述】:

假设我有一个类:

//no namespace
class User { 
    //...
}

我有一个变量:

$model = 'User';

当我当前在命名空间中时,如何实例化 new User

new $model 在我不在命名空间中时有效。但是,如果我在命名空间中,而 User 不在命名空间中呢?

这样的事情是行不通的:

namespace Admin;

class Foo {
    function fighter($model)
    {
        return new \$model;
        // syntax error, unexpected '$model'
    }
}

}

【问题讨论】:

    标签: php oop object namespaces


    【解决方案1】:

    将完整的命名空间先放在一个变量中,然后使用它。

    <?php    
    $namespace = '\\'.$model;
    
    return new $namespace
    ?>
    

    同题:Can PHP namespaces contain variables?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 2016-07-25
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多