Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 为什么可以';t我将变量传递给模型';代码点火器中的构造函数?_Php_Oop_Codeigniter_Codeigniter 2 - Fatal编程技术网

Php 为什么可以';t我将变量传递给模型';代码点火器中的构造函数?

Php 为什么可以';t我将变量传递给模型';代码点火器中的构造函数?,php,oop,codeigniter,codeigniter-2,Php,Oop,Codeigniter,Codeigniter 2,在CodeIgniter中,似乎不可能将变量传递给模型的构造函数。也许我在MVC或CodeIgniter中遗漏了一些东西,但我不明白是什么 就我而言,我应该使用Libraries而不是Model吗?(库实际接受参数) 实际上我的代码是这样的,我觉得有点奇怪: 控制器: class User extends CI_Controller { public function user($user_id) { $this->load->model('user');

在CodeIgniter中,似乎不可能将变量传递给模型的构造函数。也许我在MVC或CodeIgniter中遗漏了一些东西,但我不明白是什么

就我而言,我应该使用Libraries而不是Model吗?(库实际接受参数)

实际上我的代码是这样的,我觉得有点奇怪:

控制器:

class User extends CI_Controller {
    public function user($user_id) {
        $this->load->model('user');
        $this->user->setId($user_id);

        $data['username'] = $this->user->getName();     
        // Isn't it a bit strange ? I can load the class User even if the User doesn't mean anything ?
    }
}
型号:

class User extends CI_Model {
    private $id;
    private $name;

    public function setId($id) {
        $this->id = $id;
        // Retrieve data from DB...
        $this->name = $retrieved_data['name'];
    }

    public function getName() {
        return $this->name;
    }
}
试试这个:

控制器:

class User extends CI_Controller {

    public function user($user_id) {
        $this->load->model('user_model');

        $data['username'] = $this->user_model->getName($user_id);     
    }
}
型号:

class User_model extends CI_Model {

    public function getName($user_id) {
        //Retrieve data from DB using the $user_id variable...
        return $retrieved_data['name'];
    }
}

这似乎是一种更符合逻辑、更快的方法。不确定它是否符合代码的其余部分,但它可能会帮助您跟踪错误。

如果您将模型类重命名为(例如)user\u model,会发生什么情况?完全一样。事实上,问题在于CodeIgniter中的模型不接受构造函数()的变量。我不知道这是否正常,或者我只是缺少CodeIgniter逻辑中的某些东西(或者MVC逻辑?模型是否不应该接受其构造函数中的任何变量?),它应该接受变量。。。嗯,你有什么错误?我将为您重写它。在PHP中不能有两个相同的类名,即使您使用的是CodeIgniter。我很惊讶你居然能把模型装进去。在这段代码中,您实际上也没有“将变量传递给模型的构造函数”。@Madmartigan您是对的,对不起。我简化了stackoverflow的代码,但在我的“真实”代码中,它是用户和用户,这就是它工作的原因:)非常感谢!我现在明白多了。但我还有一个问题,和你写的有关:很高兴我能帮上忙!对于这个问题,可以把词看作是一个活格对象。