php invoke 反射,【PHP 高级特性】之反射

PHP5 开始提供了完整的反射API。有反射类(ReflectionClass)和反射函数(ReflectionFunction)等,功能大同小异,这里主要以ReflectionClass为列说明。

什么是反射

他是指PHP在运行状态中,动态的获取类、方法、属性、参数、注释等信息和动态调用对象的方法的功能。

有什么用

可以帮助我们构建复杂的,可扩的运用。比如自动加载插件,自动生成文档等

代码示例

该示例为一个通用API入口

HttpApi.php

namespace twinkle\service\http;

class HttpApi

{

private $class;

public function __construct($class)

{

$this->class = $class;

}

public function parseRequest($method,$params = [])

{

$class = new \ReflectionClass($this->class);

$instance = $class->newInstanceArgs($params);

$method = $class->getMethod($method);

$args = [];

foreach ($method->getParameters() as $param) {

$name = $param->getName();

if (isset($params[$name])) {

$args[$name] = $params[$name];

} else {

try {

$args[$name] = $param->getDefaultValue();

} catch (\Exception $e) {

throw new RequestException(

'请求参数不合未能',

500

);

}

}

}

return [$instance,$method,$args];

}

}

NotFoundService.php

namespace app\services;

use app\base\Service;

class NotFoundService extends Service

{

public function error()

{

return $this->format(['status' => 1, 'msg' => '请求不合法,请确认service和method是否存在']);

}

}

使用范例

$params = $_REQUEST;

$serviceName= isset($params['service']) ? $params['service'] : 'NotFound';

$methodName= isset($params['method']) ? $params['method'] : 'error';

$class = '\\app\\services\\' . Str::ucWords($serviceName) . 'Service';

list($instance, $method, $args) = (new HttpApi($class))->parseRequest($methodName, $params);

echo json_encode(($method->invokeArgs($instance, $args)));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值