ReflectionFunction::isAnonymous

(PHP 8 >= 8.2.0)

ReflectionFunction::isAnonymous関数が無名関数かどうかを調べる

説明

public ReflectionFunction::isAnonymous(): bool

関数が 無名関数 かどうかを調べます。

パラメータ

この関数にはパラメータはありません。

戻り値

関数が無名関数の場合、true を返します。そうでない場合、false を返します。

例1 ReflectionFunction::isAnonymous() の例

<?php

$rf
= new ReflectionFunction(function() {});
var_dump($rf->isAnonymous());

$rf = new ReflectionFunction('strlen');
var_dump($rf->isAnonymous());
?>

上の例の出力は以下となります。

bool(true)
bool(false)

参考

add a note

User Contributed Notes 2 notes

up
1
nicolasgrekas at php dot net
1 year ago
Closures can be either anonymous or not.

Here is an anonymous closure:
$c1 = function () {};

And here is a *non* anonymous closure:
$c2 = Closure::fromCallable(['Foo', 'bar']);

ReflectionFunction::isAnonymous() returns true for $c1 and false for $c2.

Before PHP 8.2, one had to do this check to decide between both:
$r = new \ReflectionFunction($c1);
$isAnonymous = false !== strpos($r->name, '{closure}');

ReflectionFunction::isAnonymous() makes it easier to check.
up
0
Taufik Nurrohman
1 year ago
You know that anonymous function is just an instance of class `Closure` so this would be equivalent to check whether a variable is an anonymous function or not:

<?php

$test
= function () {};

if (
is_callable($test) && is_object($test) && $test instanceof Closure) { /* ... */ }

?>
To Top