Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - Call method inside a model?

Tags:

codeigniter

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 (......)

like image 573
Ivanka Todorova Avatar asked May 09 '12 19:05

Ivanka Todorova


People also ask

Can we call a model from another model?

Yes, you can call a method from another model in a model in Code Igniter. You need the model you are calling a method on to be loaded. If you autoload all your models, it will always work.

How to Call controller from Model in CodeIgniter?

Create a new User. php file in application/controllers/ directory. Load Model_3 Model and call fun1() and fun2() methods. Print the response.


2 Answers

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
like image 80
Laurence Avatar answered Oct 30 '22 12:10

Laurence


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;
    }
}
like image 36
JFrez Avatar answered Oct 30 '22 11:10

JFrez