CodeIgniter - Call method inside a model?

你说的曾经没有我的故事 提交于 2019-12-29 08:40:08

问题


I have the following code:

class Badge extends CI_Model
{
    public function foo()
    {
        echo $this->bar('world');
    }

    public function bar($word)
    {
        return $word;
    }
}

But it always gives me an error on the line where echo $this->bar('world'); is.

Call to undefined method (......)


回答1:


Your not loading your model inside your controller:

public function test()
{
    $this->load->model('badge');
    $this->badge->foo();
}

Because the code works - I've just tested it by pasting using your model unedited:

class Badge extends CI_Model
{
    public function foo()
    {
        echo $this->bar('world');
    }

    public function bar($word)
    {
        return $word;
    }
}

output:

world



回答2:


In order to avoid any external call dependecy you need to get the Codeigniter instance and call the method through the instance.

class Badge extends CI_Model
{
    public function foo()
    {   
        $CI =& get_instance();

        echo $CI->Badge->bar('world');
    }

    public function bar($word)
    {
        return $word;
    }
}


来源:https://stackoverflow.com/questions/10523062/codeigniter-call-method-inside-a-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!