达到最大嵌套等级100,中止! - PHP

时间:2013-07-24 11:58:50

标签: php class

致命错误:' 100'的最大功能嵌套级别到达,流产!在第4行的C:\ wamp \ www \ int \ system \ core \ Controller.php

Call Stack
#   Time    Memory  Function    Location
1   0.0004  364608  {main}( )   ..\index.php:0
2   1.0350  433152  Bootstrap->__construct( )   ..\index.php:11
3   1.0355  438536  Welcome->__construct( ) ..\Bootstrap.php:7
4   1.0355  438536  Controller->__construct( )  ..\welcome.php:4
5   1.0356  438680  View->__construct( )    ..\Controller.php:4
6   1.0356  438680  Controller->__construct( )  ..\View.php:4

错误行:

<?php
class Controller {
    function __construct() {
        $this->view = new View(); // Error starts here
        $this->model = new Model();
        $this->tpl = new Template();
        $this->input = new Input();
        $this->lib = new Library();
        $this->session = new Session();
    }
}
?>

我该如何解决这个问题?我尝试扩展最大嵌套级别,但每次我增加它就说200,它说致命错误最高级别达到200,中止!

更新:修正:)

public function __construct() {
        self::$instance =& $this;
        $this->view = new View;
        $this->model = new Model;
        $this->tpl = new Template;
        $this->input = new Input;
        $this->lib = new Library;
        $this->session = new Session;
    }
    public static function &get_instance() {
        return self::$instance;
    }

模特:

function __get($key)
{
    $fw =& Controller::get_instance();
    return $fw->$key;
}

1 个答案:

答案 0 :(得分:4)

那是因为View的构造函数调用了Controller的构造函数,反之亦然。您需要重构代码以删除该循环引用。

我个人认为没有理由认为视图需要创建控制器甚至需要了解控制器。控制流应该是单向的:从控制器到视图。

如果需要将控制器中的功能注入视图,可以为其分配回调。像这样:

class Controller {

    function __construct() {
        $this->view = new View();
        $this->view->setFooFunction(function() {
            // do some stuff
        });
        echo $this->view->render();
    }

}


class View {

    protected $foo_function;

    public function __construct() {
        // ... no controller required :)
    }

    public function setFooFunction(Closure $function) {
        $this->foo_function = $function;
    }


    public function render() {
        $this->foo_function->__invoke();
        ... 
    }

}