ReflectionFunction::isAnonymous

(PHP 8 >= 8.2.0)

ReflectionFunction::isAnonymousChecks if a function is anonymous

Beschreibung

public ReflectionFunction::isAnonymous(): bool

Checks if a function is anonymous.

Parameter-Liste

Diese Funktion besitzt keine Parameter.

Rückgabewerte

Returns true if the function is anonymous, otherwise false.

Beispiele

Beispiel #1 ReflectionFunction::isAnonymous() example

<?php

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

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

bool(true)
bool(false)

Siehe auch

add a note add a note

User Contributed Notes 2 notes

up
2
nicolasgrekas at php dot net
2 years 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
2 years 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