calling nested function php codeigniter

自古美人都是妖i 提交于 2019-12-25 12:11:12

问题


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


回答1:


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()
  ;
}



回答2:


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.



来源:https://stackoverflow.com/questions/23017124/calling-nested-function-php-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!