合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] ## 概述 继承了 ReflectionFunctionAbstract ## 语法 ``` ReflectionFunction::__construct — Constructs a ReflectionFunction object ReflectionFunction::export — Exports function ReflectionFunction::getClosure — Returns a dynamically created closure for the function ReflectionFunction::invoke — Invokes function ReflectionFunction::invokeArgs — Invokes function args ReflectionFunction::isDisabled — Checks if function is disabled ReflectionFunction::__toString — To string ``` ## 示例 ### Hello World ``` function A($a1='',$a2=''){ return $a1.$a2; } $r = new ReflectionFunction("A"); var_dump($r->getName()); // A var_dump($r->getNumberOfParameters()); // 2 var_dump($r->invokeArgs(["hello","world"])); // helloworld var_dump($r->invoke("hello","world")); // helloworld ``` ### 判断函数,可选与否 ``` $argsArr = [ 'name' => 'Anderson Lucas Silva de Oliveira', 'age' => 21, 'hobbie' => 'Play games' ]; function processUserData($name, $age, $job = "", $hobbie = "") { $msg = "Hello $name. You have $age years old"; if (!empty($job)) { $msg .= ". Your job is $job"; } if (!empty($hobbie)) { $msg .= ". Your hobbie is $hobbie"; } echo $msg . "."; } $refFunction = new ReflectionFunction('processUserData'); $parameters = $refFunction->getParameters(); $validParameters = []; foreach ($parameters as $parameter) { // 缺少不可选函数 if (!array_key_exists($parameter->getName(), $argsArr) && !$parameter->isOptional()) { throw new DomainException('Cannot resolve the parameter' . $parameter->getName()); } // 缺少可选函数,跳过 if(!array_key_exists($parameter->getName(), $argsArr)) { continue; } $validParameters[$parameter->getName()] = $argsArr[$parameter->getName()]; } $refFunction->invoke(...$validParameters) ```