函数内的函数。? [英] Function inside a function.?
问题描述
函数x($ y){
函数y($ z){
return($ z * 2);
}
return($ y + 3);
}
$ y = 4;
$ y = x($ y)* y($ y);
echo $ y;
有什么想法吗?我很困惑。
X返回(值+3),而Y返回(值* 2)
给定值4,意味着(4 + 3)*(4 * 2)= 7 * 8 = 56
。
尽管函数的范围不受限制(这意味着您可以安全地'嵌套'函数定义),但这个特例很容易出错:
<1>您在调用 x()
之前不能调用 y()
,因为函数<$直到 x()
执行一次,c $ c> y()才会真正被定义。
<2>调用
x()
两次会导致PHP重新声明函数 y()
,导致致命错误:$ b
致命错误:无法重新声明y()
两者的解决方案都是拆分代码,以便两个函数都相互独立地声明:
函数x($ y)
{
return($ y + 3);
}
函数y($ z)
{
return($ z * 2);
}
这也可读性更强。
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.
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.
这篇关于函数内的函数。?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!