Function inside function.?

This code produces the result as 56.

function x ($y) { function y ($z) { return ($z*2); } return($y+3); } $y = 4; $y = x($y)*y($y); echo $y; 

Any idea what is going on inside? I'm confused.

+49
function php
Oct 27 '09 at 15:19
source share
6 answers

X returns (value +3), and Y returns (value * 2)

With a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56 .

Although functions are not limited in scope (which means you can safely define "socket definitions"), this specific example is error prone:

1) You cannot call y() before calling x() , because the function y() will not actually be defined until x() executes once.

2) Calling x() twice will force PHP to override the function y() , which will lead to a fatal error:

Fatal error: cannot override y ()

The solution to both issues would be to split the code, so that both functions are declared independently of each other:

 function x ($y) { return($y+3); } function y ($z) { return ($z*2); } 

It is also more readable.

+79
Oct 27 '09 at 15:24
source share
 (4+3)*(4*2) == 56 

Note that PHP does not really support "nested functions", as in the definition only in the scope of the parent function. All functions are defined globally. See docs .

+25
Oct 27 '09 at 15:22
source share

Not sure what the author of this code wanted to achieve. Defining a function inside another function does NOT mean that the inner function is visible only inside the outer function. After calling x () for the first time, the function y () will also be in the global scope.

+14
Oct 27 '09 at 15:26
source share

This is a useful concept for recursion without static properties, links, etc .:

 function getReqursiveItems($id){ $allItems = array(); function getItemms($parent_id){ return DB::findAll()->where('`parent_id` = $parent_id'); } foreach(getItems($id) as $item){ $allItems = array_merge($allItems, getItems($item->id) ); } return $allItems; } 
+6
Dec 18 '14 at 2:58
source share

You can define a function from another function. the inner function does not exist until the outer function is executed.

 echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n'; $x=x(2); echo function_exists("y") ? 'y is defined\n' : 'y is not defined \n'; 

Exit

y not defined

y is determined

The simple thing is that you cannot call the y function before executing x

+5
Aug 17 '13 at 1:31 on
source share

Your request makes 7 * 8

x(4) = 4+3 = 7 and y(4) = 4*2 = 8

what happens when the function x is called it creates the function y, it does not start it.

+3
Oct 27 '09 at 15:22
source share



All Articles