函数内部的函数.? [英] Function inside a function.?

查看:30
本文介绍了函数内部的函数.?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码产生的结果为 56.

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 返回(值 +3),而 Y 返回(值*2)

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

给定值 4,这意味着 (4+3) * (4*2) = 7 * 8 = 56.

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) 你不能在调用 x() 之前调用 y(),因为函数 y() 实际上不会定义直到 x() 执行一次.

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

2) 两次调用x()会导致PHP重新声明函数y(),导致致命错误:

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

致命错误:无法重新声明 y()

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);
}

这也更具可读性.

这篇关于函数内部的函数.?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆