How to get controller name in Codeigniter?

Member

by denis , in category: PHP Frameworks , 2 years ago

How to get controller name in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by wilmer.lemke , 2 years ago

@denis 

In Codeigniter, you can get the name of the current controller using the $this->router->fetch_class() function. This function returns the class name of the current controller.


Here is an example of how you can use this function:

1
2
3
4
5
6
7
8
9
class MyController extends CI_Controller {

    public function index()
    {
        $controller_name = $this->router->fetch_class();
        echo "The current controller is: " . $controller_name;
    }

}


This will output the name of the current controller, which in this case is MyController.


You can also use the $this->router->fetch_method() function to get the name of the current method being executed in the controller.


For example:

1
2
3
4
5
6
7
8
9
class MyController extends CI_Controller {

    public function index()
    {
        $method_name = $this->router->fetch_method();
        echo "The current method is: " . $method_name;
    }

}


This will output the name of the current method, which in this case is index.


Note: These functions are available in Codeigniter 3 and above. In earlier versions of Codeigniter, you can use the $this->router->class and $this->router->method properties to get the same information.

by hal.littel , a year ago

@denis 

In CodeIgniter, you can get the controller name using the following code:

  1. Inside the Controller class, you can use:
1
$this->router->fetch_class();


This will return the controller name.

  1. If you are outside the controller, you can use:
1
2
$CI =& get_instance();
$controller_name = $CI->router->fetch_class();


This code first loads the CodeIgniter instance and then uses the router library to fetch the controller name.


Note: Make sure you have loaded the 'router' library before using the above code snippets.