0

If I give the same name to a function in the Model of Codeigniter, that function gets called automatically when I load the model.

//controller
$this->load->model('my_model');

//model

class My_model extends CI_model {

function my_model {
}

}

In this case I don't have to call my model function like this

$this->my_model->my_model();

because loading the model calls the function as well.

Can somebody explain this behaviour? I haven't found anything in docs regarding this.

1 Answer 1

1

This is a common concept in Object-Orientated programming. The function is acting as a Constructor. The constructor is called when an instance of the object is created.

In PHP using the __construct() method is the advised way to declare a constructor for the class. However, in PHP 4, a constructor was declared using the class name, so:

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, and the class did not inherit one from a parent class, it will search for the old-style constructor function, by the name of the class.

In CodeIgniter, a model is a class. As you don't have a __construct() method in your class, PHP is treating your my_model function as the constructor for the class (as it is the same as the class name).

You may want to the following method to your model. This will stop my_model being treating as a constructor.

function __construct()
{
    // Call the Model constructor
    parent::__construct();
}

I'd personally avoid calling a method the same name as the class in PHP, as it can lead to this confusion! PHP's docs have some useful information on constructors.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.