从字符串生成动态对象


Laravel 5 Generating dynamic objects from string

我有以下目录结构(只显示重要文件):

app/
 - Http/                        
   - Controllers/
     - MyController.php         // namespace App'Http'Controllers
 - Utils/
   - InternalUtils/
     - Utility1.php             // namespace App'Utils'InternalUtils
     - Utility2.php             // namespace App'Utils'InternalUtils
     - ...
   - MyUtility.php             // namespace App'Utils

我遵循Laravel 5中可用的标准PSR-4命名空间。

MyUtility.php文件中,我试图使用以下内容:

use InternalUtils'Utility1;
use InternalUtils'Utility2;
(new Utility1);   // works
$className = 'Utility1';
(new $className);   // throws Class 'Utility1' not found

注意,每个Utility文件都有命名空间,并且包含一个与Utility1同名的类名。

对象的动态生成失败。有什么问题吗?

请按以下步骤操作

在您的Utility1.php

<?php 
namespace App'Utils'InternalUtils;
Class Utility1 
{
    //code ....
}
为了在MyUtility类中使用Utility1类,您可以导入完整的命名空间
<?php 
namespace App'Utils;
use App'Utils'InternalUtils;   
class MyUtility 
{
    //other code 
    $utility1 = new InternalUtils'Utility1();
    $utility2 = new InternalUtils'Utility2();
}