【问题标题】:Page does not load when instantiating a variable in construct在构造中实例化变量时页面不加载
【发布时间】:2017-02-06 17:46:44
【问题描述】:

这是我的代码:

这行得通

<?php

private $controller;

public function __construct() {   
}

public function randomFunc() {
    $this->controller = new Controller();
    return $this->controller;
}

?>

不起作用

<?php

private $controller;

public function __construct() {
    $this->controller = new Controller();   
}

public function randomFunc() {
    return $this->controller;
}

?>

如您所见,当我在函数中分配 $controller = new Controller() 时,它可以工作,但是当我在构造中执行它时,它不起作用。怎么会?谢谢

【问题讨论】:

  • 发布您的完整代码,包括该类以及您正在使用的任何包含/要求。
  • @Fred-ii- 这几乎是完整的代码。我正在使用 mvc,所以在它到达这个文件之前需要来自文件。

标签: php performance function model-view-controller constructor


【解决方案1】:

因为构造函数中的递归。你可以为单例做类似的事情:

protected function __construct() {}

public static function getInstance()
{
    return new Controller();
}

【讨论】:

  • 你能解释一下这是什么意思以及我做错了什么吗?抱歉,我是新手。
  • 所以你有一个在构造函数中启动的变量。但作为你自己的对象发起。以变​​量作为自己的对象。以变​​量作为自己的对象。 ...循环:)
  • 哦,我明白了,谢谢!但我也可以在每个函数中添加$this-&gt;controller = new Controller(); 对吗?
  • 停止。你在控制器类中声明它吗?如果是,Controller::getInstance() 将返回控制器类的对象。而且您不需要在类 Controller 的对象中使用类 Controller 的对象 :) 您可以只使用 $this。如果没有 - 你可以通过 $this->controller = new Controller();
  • 你是什么意思?
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 2015-04-28
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 2010-12-31
  • 2014-01-12
相关资源
最近更新 更多