Параметры закрытия подсказок - PullRequest
1 голос
/ 28 июня 2019

С помощью подсказок по типу в PHP можно ли указывать параметры замыкания?

например

function some_function(\Closure<int> $closure) {
    $closure(3);
}

// This would throw an exception
some_function(function(string $value) {
    echo $value;
});

// This would work.
some_function(function(int $value) {
    echo $value;
});

1 Ответ

2 голосов
/ 28 июня 2019

Не изначально.Вам нужно будет вручную использовать отражение .

<?php
function some_function(\Closure $closure) {

    $reflection = new ReflectionFunction($closure);
    $parameters = $reflection->getParameters();
    if(!isset($parameters[0]))
    {
        // I'm lazy but you should program this to throw a fatal exception
        echo 'some_function() expects parameter one\'s closure to expect at least one parameter'.PHP_EOL;
    }
    elseif($parameters[0]->getType().'' !== 'int') // I'm sure there is a more elegant way to achieve this...
    {
        // I'm lazy but you should program this to throw a fatal exception
        echo 'closure\'s first param should be an int'.PHP_EOL;
    }
    else
    {
        $closure(3);
    }
}

// Does not throw an exception
some_function(function(int $value) {
    var_dump($value);
});

// This throws an exception
some_function(function() {
    var_dump($value);
});

// This throws an exception
some_function(function(string $value) {
    var_dump($value);
});

Производит:

int(3)
some_function() expects parameter one's closure to expect at least one parameter
closure's first param should be an int

Также см. Вывод параметров закрытия PHP

...