Determining, if a variable is a valid closure in PHP

不羁的心 提交于 2019-12-01 02:08:21
mario

The most deterministic way to check if a callback is an actual closure is:

function is_closure($t) {
    return $t instanceof Closure;
}

All anonymous functions are represented as objects of the type Closure in PHP. (Which, coming back to above comment, happen to implement the __invoke() method.)

Phil

I think you can use instanceof Closure though the manual states this should not be relied upon. I guess it works for now.

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.

Update The Closure manual page has updated its guidance on this. It appears that this behaviour can now be relied upon.

Anonymous functions, implemented in PHP 5.3, yield objects of this type. This fact used to be considered an implementation detail, but it can now be relied upon.

php.net suggests using reflections to figure out if the variable contains a valid closure or not

I use this little helper

function isClosure($suspected_closure) {
    $reflection = new ReflectionFunction($suspected_closure);

    return (bool) $reflection->isClosure();
}

If you get an error about that does not exist ReflectionFunction, use backslash before class:

// Closure
$closure = function () {}; 
$reflection = new \ReflectionFunction($closure);
// checkout if it is a closure
$test->isTrue($reflection->isClosure());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!