Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

ReflectionFunction

Inspect or invoke a named function or Closure.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new ReflectionFunction($nameOrClosure)

Inspect or invoke a named function or Closure. Required parameter count excludes optional parameters, and invokeArgs uses array entries for the call. In PHP 8 string keys in invokeArgs are parameter names, so their order need not match the declaration. An unknown function name raises ReflectionException.

function cost(int $n,int $fee=2): int{return $n-$fee;}
$r=new ReflectionFunction("cost");
echo json_encode([$r->getNumberOfParameters(),$r->getNumberOfRequiredParameters(),$r->invokeArgs(["fee"=>3,"n"=>5])]);
[2,1,2]

Examples

<?php
function cost(int $n,int $fee=2): int{return $n-$fee;}
$r=new ReflectionFunction("cost");
echo json_encode([$r->getNumberOfParameters(),$r->getNumberOfRequiredParameters(),$r->invokeArgs(["fee"=>3,"n"=>5])]);

Result

[2,1,2]

Sources