<?phpnamespace console\component\reflect;use ReflectionClass;use Exception;use ReflectionException;trait Reflect{ /** * 反射调用方法 * * 示例: * $clsName = FixOrder::class; * $funcName = 'receivedNotBuyPicc'; * $parameter = ['order_id' => 123456, 'a' => 222]; * list($code, $ret) = $this->reflectCall($clsName, $funcName, $parameter); * if ($code === false) { * throw new Exception($ret); * } * @param string $clsName * @param string $funcName * @param $parameter * @return array */ public function reflectCall(string $clsName, string $funcName, $parameter) { try { // 类 try { $reflection = new ReflectionClass($clsName); } catch (ReflectionException $e) { throw new Exception('类不存在'); } // 查看是否可以实例化 if (!$reflection->isInstantiable()) { throw new Exception('类不可实例化'); } // 构造方法 $constructor = $reflection->getConstructor(); if ($constructor !== null) { foreach ($constructor->getParameters() as $param) { if (!$param->isDefaultValueAvailable()) { throw new Exception('需要处理构造方法'); } } } // 目标方法 try { $method = $reflection->getMethod($funcName); } catch (ReflectionException $e) { throw new Exception('方法不存在'); } // 方法基本情况 if (!$method->isPublic() || $method->isAbstract()) { throw new Exception('方法不可调用'); } // 方法参数 $args = []; if ($funcParams = $method->getParameters()) { foreach ($funcParams as $param) { if (!isset($parameter[$param->name])) { throw new Exception('缺少参数' . $param->name); } $args[] = $parameter[$param->name]; } } $cls = $reflection->newInstance(); $ret = $method->invokeArgs($cls, $args); return [true, $ret]; } catch (Exception $e) { return [false, $e->getMessage()]; } }}