CodeIgniter - Call method inside a model?

2019-01-28 03:10发布

问题:

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;
    }
}


标签: codeigniter