Search code examples
phpfunctioncodeigniternested-function

calling nested function php codeigniter


i am trying to call a function which is nested under other function consider a example:

function _get_stats() {
    function _get_string() {
        $string = 'Nested Function Not Working';
        return $string;
    }
 }

 public function index() {
    $data['title'] = $this->_get_stats() . _get_string();
    $this->load->view('home', $data);
 }

now when i run the page in web browser blank page is displayed.

any suggestion or help would be a great help for me.. thanks in advance


Solution

  • The function is not really nested, but calling _get_stats() will cause _get_string to be declared. There is no such thing as nested functions or classes in PHP.

    Calling _get_stats() twice or more will cause an error, saying that function _get_string() already exists and cannot be redeclared.

    Calling _get_string() before _get_stats() will raise an error saying that function _get_string() does not exist`.

    In your case, if you really want to do this (and it is a bad practice), do the following:

    protected function _get_stats() {
        if (!function_exists("_get_string")){
            function _get_string() {
                $string = 'Nested Function Not Working';
                return $string;
            }
        }
    }
    
    public function index() {
        $this->_get_stats(); //This function just declares another global function.
        $data['title'] = _get_string(); //Call the previously declared global function.
        $this->load->view('home', $data);
    }
    

    BUT What you are looking for is probably method chaining. In this case you method must return a valid object which contains the needed functions.

    Example:

    protected function getOne(){
      //Do stuff
      return $this ;
    }
    
    protected function getTwo(){
      //Do stuff ;
      return $this ;
    }
    
    public function index(){
      $this
        ->getOne()
        ->getTwo()
      ;
    }