首页 > 解决方案 > 特定的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

解决方案


以下将满足您的示例使用:

<?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返回结果。


推荐阅读