Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP MVC:注册表在到达控制器的途中丢失_Php_Oop - Fatal编程技术网

PHP MVC:注册表在到达控制器的途中丢失

PHP MVC:注册表在到达控制器的途中丢失,php,oop,Php,Oop,我正在处理注册表对象,但在将注册表对象传递到控制器类时遇到问题 在我的Router类中,loadController()方法确定要加载的控制器并对其进行实例化。在此过程中,它向控制器传递一个注册表对象,其中包含一个模板对象: class Router { private $registry; // passed to Router's constructor public $file; // contains

我正在处理注册表对象,但在将注册表对象传递到控制器类时遇到问题

在我的Router类中,loadController()方法确定要加载的控制器并对其进行实例化。在此过程中,它向控制器传递一个注册表对象,其中包含一个模板对象:

class Router
{
    private $registry;                // passed to Router's constructor
    public $file;                     // contains 'root/application/Index.php'
    public $controller;               // contains 'Index'

    public function loadController()
    {
        $this->getController();       // sets $this->file, $this->controller
        include $this->file;          // loads Index controller class definition
        $class = $this->controller;
        $controller = new $class($this->registry);
    }
}
从Xdebug中,我知道路由器的$registry属性在作为参数传递给索引的构造函数之前拥有它应该拥有的一切

但是,$registry无法使其完整地索引。以下是索引及其父控制器的类定义:

abstract class Controller
{
    protected $registry;

    function __construct($registry)
    {
        $this->registry = $registry;
    }
    abstract function index();
}

class Index extends Controller
{
    public function index()
    {
        $this->registry->template->welcome = 'Welcome';
        $this->registry->template->show('index');
    }
}
使用如图所示的代码,我得到以下错误消息:“调用…Index.php中未定义的方法stdClass::show()

在索引中,Xdebug将$registry显示为null,因此我知道它是从父级继承的。但是,在创建新索引对象的代码和索引类定义之间的某个地方,$registry会丢失

调试时,我发现从等式中删除控制器类可以阻止错误的发生:

class Index // extends Controller
{
    private $registry;

    function __construct($registry)
    {
        $this->registry = $registry;
    }

    public function index()
    {
        $this->registry->template->welcome = 'Welcome';
        $this->registry->template->show('index');
    }
}
当然,这并不能真正解决任何问题,因为我仍然需要Controller类,但希望它能帮助解决这个问题

有人知道为什么$registry传递到Index时会丢失它的内容吗?

这应该可以:

class Index extends Controller
{
    public function __construct( $registry )
    {
         parent::__construct( $registry );
    }

    public function index()
    {
        $this->registry->template->welcome = 'Welcome';
        $this->registry->template->show('index');
    }
}
在PHP中,构造函数不是继承的


a另外,您可能会从观看本视频和其他系列视频中受益:

感谢您提供的精彩链接-我已经看了三遍,该系列对我帮助很大。