是什么导致此 "Missing argument 2 for Categories::posts()" 错误?

What causes this "Missing argument 2 for Categories::posts()" error?

我正在开发一个小型博客应用程序。它的后端和前端之间有明显的分离。

后端是一个 API,用 Codeigniter 3 制作,可以输出页面、posts、分页等

在此 API 中, 帖子 控制器中有一个 _initPagination(),整个站点都在使用它:

private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
//load and configure pagination 
    $this->load->library('pagination');
    $config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;
    $config['query_string_segment'] = $query_string_segment; 
    $config['enable_query_strings'] =TRUE;
    $config['reuse_query_string'] =TRUE;
    $config['total_rows'] = $totalRows;
    $config['per_page'] = 12;
    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        $_GET[$config['query_string_segment']] = 1;
    }
    $this->pagination->initialize($config);

    $limit = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

    return ['limit' => $limit, 'offset' => $offset];
}

类别 控制器显示 post 按类别:

public function posts($path, $category_id) {
    //load and configure pagination 
    $this->load->library('pagination');
    $config['base_url'] = "http://".$_SERVER['HTTP_HOST'] . $path;
    $config['base_url'] = base_url('/categories/posts/' . $category_id);
    $config['query_string_segment'] = 'page';
    $config['total_rows'] = $this->Posts_model->get_num_rows_by_category($category_id);
    $config['per_page'] = 12;

    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
        $_GET[$config['query_string_segment']] = 1;
    }

    $limit = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;
    $this->pagination->initialize($config);

    $data = $this->Static_model->get_static_data();
    $data['pagination'] = $this->pagination->create_links();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();
    $data['category_name'] = $this->Categories_model->get_category($category_id)->name;
    $data['posts'] = $this->Posts_model->get_posts_by_category($category_id, $limit, $offset);

    // All posts in a CATEGORY
    $this->output->set_content_type('application/json')->set_output(json_encode($data,JSON_PRETTY_PRINT));
}

上面的代码有一个我找不到的错误。应用程序抛出的错误消息是:

Missing argument 2 for Categories::posts() 

我的错误在哪里?

这意味着您已将 1 个参数而不是 2 个参数传递给此方法。发送 $path$category_id

如果你想说有时第二个参数可能不存在,那么重写如下:

public function posts($path, $category_id = null) {

在这种情况下,$category_id 默认为 null

public function posts($path = null, $category_id) {

在这种情况下,$path 默认为 null