【问题标题】:New object with name in variable变量中具有名称的新对象
【发布时间】:2018-08-13 08:37:11
【问题描述】:

我正在尝试使用动态路径启动对象。我有带有模型名称的变量$model

$model = "foo";
$class = new \Path\To\$model();

我得到了错误

Parse error: syntax error, unexpected '$model' (T_VARIABLE), expecting identifier (T_STRING)

如果我尝试$class = new \Path\To\{$model}(); 我收到错误

 Parse error: syntax error, unexpected '{', expecting identifier (T_STRING)

当我尝试时

namespace \App\Models
$class = new $model(); 

我收到错误Class 'foo' not found

当我尝试$class = new \Path\To\foo(); 时,它可以工作。

有什么想法吗?

【问题讨论】:

    标签: php laravel class object model


    【解决方案1】:

    试试:

    $class = "\Path\To\foo";
    $object = new $class();
    

    或者:

    use Path\To\foo;
    $class = foo::class;
    $object = new $class();
    

    【讨论】:

      【解决方案2】:

      您可以将路径存储在变量中:

      $path = "\Path\To\\";
      

      然后生成这样的类名:

      $className = $path.$model;
      $class = new $className(); 
      

      【讨论】:

        猜你喜欢
        • 2013-06-16
        • 2012-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-19
        • 1970-01-01
        相关资源
        最近更新 更多