How to call function inside function in codeigniter?

by wilmer.lemke , in category: PHP Frameworks , 21 days ago

How to call function inside function in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aniya.jaskolski , 20 days ago

@wilmer.lemke 

To call a function inside another function in CodeIgniter, you can simply use the $this keyword followed by the function name within the same controller or model.


Here is an example inside a controller:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class ExampleController extends CI_Controller {

    public function first_function() {
        // Call second_function inside first_function
        $this->second_function();
    }

    public function second_function() {
        echo "This is the second function";
    }
}


Make sure to include the appropriate model or library if the function you are calling is defined in a different class.


If you are calling a function from a different controller, you can use the following code:

1
2
$controller = new OtherController();
$controller->functionName();


Note: It is generally not recommended to call one controller function from another as it may lead to tight coupling and can make the code harder to maintain. Consider refactoring the code to separate out common functionality into a service or helper class that can be used across multiple controllers.