Search code examples
phpcodeigniternusoap

How to Access $this variable inside nested functions in codeigniter?


I have a controller for Nu soap WSDL Like:

    class webservice extends CI_Controller
        {
        function index()
        {
              $this->load->library('encrypt');
              $this->load->model('MWSDl');
//...
            function buy($apicode)
            {
                if(!$this->MWSDl->check_gateway($apicode)) //Error occurred  php Cannot find "$this" Variable
            }
//...
            $this->nusoap_server->service(file_get_contents("php://input"));
        }
    }

How to Access $this inside buy function?
I tried by global $this But Error occurred!
Error:
Fatal error: Using $this when not in object context in \controllers\webservice.php on line 9


Solution

  • You are going wrong about the whole concept. PHP is not Javascript.You shouldn't nest functions, specially not when using OOP frameworks. If you run function index twice, the second time you will probably get an error that function buy is already declared since first run of index will declare function buy.

    I would declare them as class member functions / methods.

    class Webservice extends CI_Controller {
    
            function __construct()
            {
                 parent::construct();
                 $this->load->library('encrypt');
                 $this->load->model('MWSDl');
            }
    
            function index()
            {
                // do something like
                $apicode = 'xxxxxx';
                $this->buy($apicode);
    
                //or  what ever else you need to do
            }
    
    
            function buy($apicode)
            {
                if(!$this->MWSDl->check_gateway($apicode)) {
    
                    $this->nusoap_server->service(file_get_contents("php://input"));
    
                }
            }
        }
    

    No need to use globals in codeigniter.

    Let me know if this helps.