1 function foo($i){
2 return bar($i)*4;
3 function bar($i){
4 return $i*4;
5 }
6 }
7 echo foo(4);
return
Fatal error: Call to undefined function bar() in /var/www/index.php on line 2
why doesn't it work? it works well in javascript, while it works when i do this:
function foo($i){
return bar($i)*4;
}
function bar($i){
return $i*4;
}
6 Answers 6
Define the function above your return value, otherwise it never gets executed.
<?php
function foo($i){
function bar($i){
return $i*4;
}
return bar($i)*4;
}
echo foo(4);
?>
1 Comment
It doesn't work as you are calling bar() before it has been created. See example 2 here:- http://www.php.net/manual/en/functions.user-defined.php
Comments
Your code never reach function bar(...)
, therefore it's never defined.
You need to put your bar()
function before your foo()
or before the return bar
. (Answer based on your first example).
With your second example you probably define bar()
before you use foo()
therefore bar()
is defined and it works fine.
So as long as you have your function defined when you hit a certain spot in your code it works fine, no matter if it's called from within another function.
Comments
If you define function within another function, it can be accessed directly, but after calling parent function. For example:
function a () {
function b() {
echo "I am b.";
}
echo "I am a.<br/>";
}
//b(); Fatal error: Call to undefined function b() in E:\..\func.php on line 8
a(); // Print I am a.
b(); // Print I am b.
Comments
Execution not execute after return statement
change your code like this
function foo($i){
function bar($i){
return $i*4;
}
return bar($i)*4;
}
echo foo(4);
Comments
For the sake of having a "recent" answer, here's what I did:
function printRx($conn, $patient)
{
function rows($rows, $tod)
{
for ($x = 0; $x < count($tod); $x++) {
if ($tod[$x] == 1) {
$rows++;
break;
}
}
return $rows;
}
$tod['prn'] = (explode('|', $row['prn'])) ?? null;
$rows = rows($rows, $tod['prn']);
return;
}
Works beautifully
var f = function () {}
andfunction f() {}
(wishful thinking?).