调用嵌套函数php代码点火器


calling nested function php codeigniter

我正在尝试调用一个function,它是其他function下的nested。考虑一个示例:

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

现在,当我在web浏览器中运行页面时,会显示blank页面。

任何建议或帮助对我来说都是一个很大的帮助。提前感谢

函数并不是真正嵌套的,但调用_get_stats()会导致声明_get_string。PHP中不存在嵌套函数或类。

调用_get_stats()两次或两次以上会导致错误,表示函数_get_string()已经存在,无法重新声明。

_get_stats()之前调用_get_string()将引发一个错误,说明函数_get_string()不存在。

在您的情况下,如果您真的想这样做(这是一种糟糕的做法),请执行以下操作:

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

但是你要找的可能是method chaining。在这种情况下,方法必须返回一个包含所需函数的有效对象。

示例:

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

如果您有一个空白页面,则可能是500"服务器错误"响应,即PHP代码中的致命错误。

_get_string将在PHP执行达到其声明时定义,即在_get_stats中执行此声明时定义。

index()中,_get_string可能在您调用它的那一刻还没有声明

尽管如此,由于嵌套函数是在全局命名空间中定义的(例如,与JS相反),您可能需要移动_get_string声明。