php - fatal error : Uncaught Error: Class not found in dynamic variable namespace

标签 php namespaces

我有这个主 Controller :

namespace App\Core;
/**
* Controller class
*/

class Controller
{
    /** @var View View The view object */
    public $View;
    public $templates;
    /**
     * Construct the (base) controller. This happens when a real controller is constructed, like in
     */
    public function __construct()
    {

    }

    public function loadModel($name) {

        $path = '\\App\\Front\\Model\\'.$name; // Not Work

        //$this->model = new \App\Front\Model\IndexModel(); Work

        $this->model = new $path;

        return $this->model;

    }
}

在 IndexController 我有:
namespace App\Front\Controller;

use App\Front\Model\IndexModel;

class IndexController extends \App\Core\Controller {

    public function index(){
        $this->loadModel('IndexModel()')->test();
    }
}

现在在行动中我看到错误:

Fatal error: Uncaught Error: Class '\App\Front\Model\IndexModel()' not found in /Applications/MAMP/htdocs/mvc/application/Core/Controller.php:64



如何修复错误?

最佳答案

您需要删除 ()从字符串:

$this->loadModel('IndexModel')->test();

没有必要()创建没有参数的新实例时。如果你确实想要它,或者你想传递一些参数,你需要在实例化的变量之后添加它们:
new $path('someArgument');

关于php - fatal error : Uncaught Error: Class not found in dynamic variable namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341720/

相关文章:

php - Yii 外键验证规则

php - 如何使用 PHP 将所有字符转换为等效的 html 实体

c++ - 为什么 "#define A"会干扰 "namespace A{}"?

.net - 拥有多个 DLL 好还是单个大 DLL 好?

linux - Nginx 负载均衡器有两个负载均衡 nginx+php-fpm (主脚本未知)错误

php - cakephp 1.3 对habtm相关数据进行分页

javascript - 如何验证动态创建的具有时间值的文本框

clojure - 为什么在导入 Clojure 协议(protocol)时出现 IllegalArgumentException "interface is not a protocol"?

c# - 如何在 VS Code 中快速添加缺少的命名空间?

c++ - 在友元声明中使用限定名称的规则是什么?