0

我正在尝试调用function其他nested考虑function示例:

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页面会显示出来。

任何建议或帮助都会对我有很大帮助..提前谢谢

4

2 回答 2

1

该函数并不是真正嵌套的,但调用_get_stats()会导致_get_string被声明。PHP 中没有嵌套函数或类之类的东西。

调用_get_stats()两次以上会报错,说函数_get_string()已经存在,不能重新声明。

_get_string()之前调用_get_stats()会引发一个错误,指出该函数_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()
  ;
}
于 2014-04-11T15:59:26.983 回答
1

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

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

index(),中,_get_string您调用它时可能尚未声明。

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

于 2014-04-11T16:01:10.473 回答