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
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.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:
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: