簡體   English   中英

類型提示關閉參數

[英]Type-hint closure parameters

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

不是本地的。 您將需要手動使用反射

<?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關閉參數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM