我正在尝试调用一个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
声明。