Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inside a function.?

Tags:

function

php

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 inside? I am confused.

like image 393
Posto Avatar asked Oct 27 '09 15:10

Posto


People also ask

What is a function inside a function called?

A function defined inside another function is known as an inner function or a nested function.

Can you put a function inside of a function?

We can declare a function inside a function, but it's not a nested function. Because nested functions definitions can not access local variables of the surrounding blocks, they can access only global variables of the containing module.

How do you use a function within a function?

To call a function inside another function, define the inner function inside the outer function and invoke it. When using the function keyword, the function gets hoisted to the top of the scope and can be called from anywhere inside of the outer function.

Is function inside a function bad?

no, there's nothing wrong with that at all, and in js, it's usually a good thing. the inside functions may not be a pure function, if they rely on closure variables. If you don't need a closure or don't need to worry about polluting your namespace, write it as a sibling.


2 Answers

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

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

Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:

1) You can't call y() before calling x(), because function y() won't actually be defined until x() has executed once.

2) Calling x() twice will cause PHP to redeclare function y(), leading to a fatal error:

Fatal error: Cannot redeclare y()

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

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

This is also a lot more readable.

like image 89
Duroth Avatar answered Sep 24 '22 00:09

Duroth


(4+3)*(4*2) == 56 

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

like image 44
Lukáš Lalinský Avatar answered Sep 20 '22 00:09

Lukáš Lalinský