Determining, if a variable is a valid closure in PHP

醉酒当歌 提交于 2019-12-06 16:41:04

问题


Using the following function:

function is_closure($t) { return ( !is_string($t) && is_callable($t)); }

Can this return true for anything else, than an anonymous closure function? If so, what would be the correct way to determine, if a variable is a closure?

Many thanks


回答1:


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.)




回答2:


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.




回答3:


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



回答4:


This is supported with Reflection http://www.php.net/manual/en/reflectionfunctionabstract.isclosure.php




回答5:


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());


来源:https://stackoverflow.com/questions/7101469/determining-if-a-variable-is-a-valid-closure-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!