calling nested function php codeigniter

2019-08-30 05:08发布

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

2条回答
Anthone
2楼-- · 2019-08-30 05:35

If you have a blank page, it may be a 500 "server error" response, i.e. fatal error in the PHP code.

_get_string will be defined when PHP execution reaches its declaration, i.e. in _get_stats when this one is executed.

In index() , _get_string probably is not declared yet at the moment you're invoking it.

As nested functions are nevertheless defined in the global namespace (contrary to JS for example), you may want to move the _get_string declaration.

查看更多
forever°为你锁心
3楼-- · 2019-08-30 05:44

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()
  ;
}
查看更多
登录 后发表回答