Hey everyone!

Ever since I wrote a few posts on CodeIgniter and published Facebook PHP SDK for CodeIgniter library, and I have been asked this very same question many times. How to get name of current controller (Class) and method (Function)?

Its pretty simple one line code and can be easily found through Google. But there’s a lot of confusion and multiple codes depending on different versions. So I decided to share the code which I have been using on every website that I develop based on CI and works perfectly on the current version of CI v2.1.4.

That’s it! Just simple one line code. But there’s another thing I would like to share, Which is the best way to declare such variables so its available on all controllers and methods?

Obviously you are not going to execute same line on every controller or method (Seriously that’s a bad idea). This is really important as you will not be using just these 2 variables, you may also want site settings and menus to be available everywhere. So my idea to implement this is declare those variables in Controller.php file in CI_Installation/System/Core folder.

Instead of declaring $data variable to load view in every controller or every method. I prefer declaring it as array in Core CI_Controller class which is parent class of all controllers. So the $this->data variable is available and editable everywhere. Not just for variables, If you can also do some pre-processing such as loading data from cache and request validations by declaring functions and invoking them in constructor of CI_Controller class.

Here’s the sample code, this will give you an idea how I do it for my projects and if you have any better way, please feel free to share with me in comments!

Signing off! Puneet

5 Responses

  1. with this method would I be able to load my controller class ControllerCommonWelcome but the file would still remain welcome.php

  2. Thanks! The idea is useful!

    But, is this better to use “MY_Controller extends CI_Controller” instead of modifing CI_Controller directly?

  3. You can use get_class($this) for class and global constant __FUNCTION__ to get the current function name.

Leave a Reply

Your email address will not be published. Required fields are marked *