0

I have a MY_Controller php file with MY_Controller class and Other_Controller that extends My_Controller class in my application/core folder.

class MY_Controller extends CI_Controller 
{
    function __construct()
    {
        parent::__construct();
    }
    function SomeMethod()
    {
        echo "method MY_Controller";
    }
}
class Other_Controller extends My_Controller 
{
    function __construct()
    {
       parent::__construct();
    }
}

On my Application/controller folder :

    Class Main extends Other_Controller
    { include(APPPATH.'core/Other_Controller.php');
        function __construct()
        {
            parent::__construct();
            // Call SomeMethod function name?
        }
    }

Can I call SomeMethod function from MY_Controller to Main Controller?

1 Answer 1

1

Yes, you can, simply use parent keyword same way as you're using it with constructor:

class Main extends Other_Controller
{
    function __construct()
    {
        parent::__construct();
        parent::SomeMethod(); // echoes "method MY_Controller"
    }
}

In case Other_Controller class overrides MY_Controller::SomeMethod, you still can call the original SomeMethod from the Main class by using full class name and scope resolution operator :::

class MY_Controller extends CI_Controller 
{
    function __construct()
    {
        parent::__construct();
    }

    function SomeMethod()
    {
        echo "method MY_Controller";
    }
}

class Other_Controller extends My_Controller 
{
    function __construct()
    {
       parent::__construct();
    }

    function SomeMethod()
    {
        echo "method Other_Controller";
    }
}

class Main extends Other_Controller
{
    function __construct()
    {
        parent::__construct();
        parent::SomeMethod(); // echoes "method Other_Controller"
        MY_Controller::SomeMethod(); // echoes "method MY_Controller"
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

how to change MY_Controller::SomeMethod(); calling method to "$this->" method calling?
You don't need to change it to $this->SomeMethod(), because SomeMethod actually don't belong to $this class
Just FYI, MY_Controller::SomeMethod() works both for static and non-static methods
anyway, I just wanna know, could MY_Controller::SomeMethod() calling method be change to MY_Controller -> SomeMethod() ? thank you
1. If there is no overriding of SomeMethod in Other_Controller class, you can use $this->SomeMethod() - it will work just fine. 2. If SomeMethod is overridden, then MY_Controller::SomeMethod() is your best option. Unfortunately, you can't use MY_Controller -> SomeMethod()
|

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.