我一直在制作自己的PHP框架,我遇到了这个问题,我找不到答案,所以为了将其作为模式,我以这种方式编码:
class post_control extends LoopControl
{
var $model;
function __construct()
{
parent::__construct();
$classname = get_class($this);
$this->model = new $classname();
}
}
我收到此错误:
致命错误:第 23 行的/opt/lampp/htdocs/LoopWork/admin/core/model/Form .class.php中允许的 134217728 字节内存大小耗尽(尝试分配 77 个字节<</p>
问题2:
我真的用了这么多内存?如何?
事实1:
如果我编写新的 post_model(); 我没有收到此错误。
考虑到事实1,我认为这些对阶级采取新立场的方式之间存在差异。
已经谢谢了!
在您的示例中,您基本上创建了无限次post_control
的实例。这就是脚本消耗所有内存的原因。
class post_control extends LoopControl
{
var $model;
function __construct()
{
parent::__construct();
$classname = get_class($this);
$this->model = new $classname(); // this is the line where you instantiate a
//new post_control, and again post_control constructor is call, and a new instance
//is created.. and so on for infinite times
}
}
是的,您正在用完系统的所有内存。这是因为您的构造函数创建了一个无限递归:
class post_control extends LoopControl
{
var $model;
function __construct()
{
parent::__construct();
$classname = get_class($this); // evaluates to 'post_control'
$this->model = new $classname(); // equiv to new post_control();
}
}
在创建post_control
时,它将尝试为其$model
属性创建另一个post_control
。反过来,这将调用相同的构造函数,该构造函数将尝试为自己$model
创建新的post_control
,依此类推,直到永恒......
$classname
是post_control
,而不是在您的示例中post_model
。您正在递归调用构造函数。无限递归会消耗所有可用内存,从而产生致命错误。