【问题标题】:PHP OOP: Missing argument from constructPHP OOP:构造中缺少参数
【发布时间】:2014-10-08 18:37:09
【问题描述】:

var_dump正确执行后出现以下通知和警告;即var_dump($params) 有效,但之后会出现这些错误。

我发现在Models_Index 类中使用public function __construct($params='') 会导致忽略这些错误的发生,但我不确定它们为什么会发生,或者为什么这会有所帮助。

警告:Models_Index::__construct() 缺少参数 1

注意:未定义变量:第 7 行的 models_index 类中的参数

class Router {
  public function __construct(){
    $cont = new Controller('Passing params');
  }
} 
new Router;

class Controller extends Core_Controller {
  public function __construct($params) {  
    $model = $this->model("Models_Index", $params);
  }
}

class Core_Controller {
  protected function model($model, $params) {
    $model = new Models_Index($params);
    return new $model;
  }
}

class Models_Index extends Core_Model {
  public function __construct($params) {
    var_dump($params); // line 7
  }
}

【问题讨论】:

  • 您的 Controller 类没有构造函数,那么您希望 PHP 对您尝试使用 new Controller($params) 传递给它的 $params 做什么?
  • $params发送到Models_Index构造函数时是不是一个值?
  • @MarcB,是的。
  • @jack:哎呀。对不起。在这里对视。
  • @MarcB 别担心,哈哈。

标签: php class constructor


【解决方案1】:

问题是你返回new $model:

return new $model;

.. 等于

return new Models_Index();

【讨论】:

  • 不完全是,它等于:new Models_Index($params),所以我返回了new new Models_Index($params) - 这导致了错误。不过,你让我走上了正轨,所以 +1。
  • 好吧,我的错误,但我认为它没有意义。
  • 实际上,@msfoster 是正确的,它等于new Models_Index()。如果它触发了new Models_Index($params),你只会看到输出两次而没有错误。这就是它警告参数丢失的原因。
猜你喜欢
  • 2014-05-06
  • 2015-06-30
  • 2011-04-27
  • 2012-05-09
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
相关资源
最近更新 更多