如何在PHP 7中动态声明函数的返回类型

时间:2019-06-19 13:35:58

标签: php return-type type-hinting

我创建了一种方法来动态地遍历对象方法,并使用将充当工厂的匿名函数创建数组。

我有一个问题,如何动态声明匿名函数的返回类型。我找不到正确的语法,也不确定在PHP中是否有可能。

我想在简化版本中创建类似的内容:

$services = [];
$object_class = get_class($object);
$method_names = get_class_methods($object_class);

// go through all object methods
foreach ($method_names as $method_name) {
    // get return type of this method
    $method = new ReflectionMethod($object_class, $method_name);
    $type = $method->getReturnType();

    // use it as return type for this anonymous function (not working)
    $services[$method_name] = function() use ($object, $method_name): $type {
        return call_user_func([$object, $method_name]);
    };
}

但是我在这里遇到语法错误。

1 个答案:

答案 0 :(得分:0)

我不确定这是否可行,即使PHP可以执行所有魔术操作。您可以做的事情是这样的:

git remote prune origin

或抛出一些不匹配的异常。

相关问题