Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function within a function PHP

Tags:

php

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;
   }
like image 896
theHack Avatar asked Jun 25 '11 16:06

theHack


2 Answers

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);
?>
like image 123
Percy Avatar answered Oct 19 '22 23:10

Percy


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

like image 42
vascowhite Avatar answered Oct 20 '22 00:10

vascowhite