该函数并不是真正嵌套的,但调用_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()
;
}