php - 特定的php功能
问题描述
我的团队领导前段时间问了这个问题,我不明白:
Implement function calc()
Please, implement function calc so code below works:
$sum = function($a, $b) { return $a + $b; };
calc(5)(3)(2)($sum); // 10
calc(1)(2)($sum); // 3
calc(2)(3)('pow'); // 8
那么,有人可以解释一下它是什么,也许还有一些关于这个功能的链接
解决方案
以下将满足您的示例使用:
<?php
function calc($input)
{
static $args = [];
if(is_callable($input)) {
$carry = array_shift($args);
$result = array_reduce($args, $input, $carry);
$args = []; // Clear the arguments.
return $result;
} else {
$args[] = $input; // Add arguments to the stack.
return __FUNCTION__;
}
}
$sum = function($a, $b) {
return $a + $b;
};
echo
calc(5)(3)(2)($sum), "\n",
calc(1)(2)($sum), "\n",
calc(2)(3)('pow'), "\n",
calc(5)(2)(2)('pow');
输出:
10
3
8
625
解释:
当calc
使用单个参数(不是可调用的)调用时,输入被推送到数组并返回函数的名称,此处为“calc”。
calc(2)(3)
会将 2 添加到静态数组(这将在后续函数调用之间持续存在),并返回函数名称。所以这就变成calc(3)
了,之前的调用具有将 2 存储在的副作用$args
。
如果传递的参数是可调用的。 array_reduce将从左到右传递成对的参数$args
给可调用对象,用每次迭代的结果播种后续调用。
array_reduce([1,2,3], 'pow', $initial)
类似于以下内容:
$result = pow($initial, 1);
$result = pow($result, 2);
$result = pow($result, 3);
但是,我们需要使用array_shift从$args
数组中删除第一项作为调用第一次迭代的种子pow
:
这样就变成了array_reduce([2,3], 'pow', 1)
。
然后我们清除参数列表,否则后续调用calc
将再次使用这些参数,并array_reduce
返回结果。
推荐阅读
- python - Networkx:图中节点的标签
- tcp-keepalive - postgres hikari 池活动连接(+备用连接)在 Docker 中的启动请求 5-8 分钟后断开连接
- java - Keycloak 中的 Rest Template PUT 方法
- android - 我该如何解决这个问题)
- ruby-on-rails - gawd awesomel rails 3.0.0 bundler 无法加载此类文件 rubygems install insanity
- c# - 如何在运行时允许用户创建新的 Picturebox Visual Studio C# Windows Forms Apps
- php - 库的扩展名和二进制文件是什么意思?
- flutter - 当用户在 Flutter 中离开当前屏幕时调用函数
- ios - 相机沿x轴移动时如何限制SCNNode移动?
- javascript - 如何使用 JINJAVA 将 Java 字符串值或字符串列表传递给 javascript