2 Star 2 Fork 0

纸喵软件 / frame-php

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Without author's permission, this code is only for learning and cannot be used for other purposes.
Clone or download
Reflection.php 3.35 KB
Copy Edit Web IDE Raw Blame History
<?php
/**
* 反射类- 用于解析控制器中方法参数
* Created by PhpStorm.
* User: 倒霉狐狸
* Date: 2018-08-14
* Time: 11:42
*/
namespace zhimiao;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Exception;
class Reflection
{
/**
* 调用反射执行类的方法 支持参数绑定
* @access public
* @param mixed $method 方法
* @param array $vars 参数
* @return mixed
*/
public function invokeMethod($method, $vars = [])
{
try {
if (is_array($method)) {
$class = is_object($method[0]) ? $method[0] : $this->invokeClass($method[0]);
$reflect = new ReflectionMethod($class, $method[1]);
} else {
// 静态方法
$reflect = new ReflectionMethod($method);
}
if (!$reflect->isPublic()) {
throw new ReflectionException('the function is not found [-.0]');
}
$args = $this->bindParams($reflect, $vars);
return $reflect->invokeArgs(isset($class) ? $class : null, $args);
} catch (Exception $e) {
Response::json(-10001, null, $e->getMessage());
}
}
/**
* 调用反射执行类的实例化 支持依赖注入
* @access public
* @param string $class 类名
* @param array $vars 参数
* @return mixed
*/
public function invokeClass($class, $vars = [])
{
try {
$reflect = new ReflectionClass($class);
if ($reflect->hasMethod('__make')) {
$method = new ReflectionMethod($class, '__make');
if ($method->isPublic() && $method->isStatic()) {
$args = $this->bindParams($method, $vars);
return $method->invokeArgs(null, $args);
}
}
$constructor = $reflect->getConstructor();
$args = $constructor ? $this->bindParams($constructor, $vars) : [];
return $reflect->newInstanceArgs($args);
} catch (Exception $e) {
Response::json(-10000, null, $e->getMessage());
}
}
/**
* 绑定参数
* @access protected
* @param \ReflectionMethod|\ReflectionFunction $reflect 反射类
* @param array $vars 参数
* @return array
*/
protected function bindParams($reflect, $vars = [])
{
if ($reflect->getNumberOfParameters() == 0) {
return [];
}
// 判断数组类型 数字数组时按顺序绑定参数
reset($vars);
$type = key($vars) === 0 ? 1 : 0;
$params = $reflect->getParameters();
foreach ($params as $param) {
$name = $param->getName();
$class = $param->getClass();
if ($class) {
$args[] = $this->getObjectParam($class->getName(), $vars);
} elseif (1 == $type && !empty($vars)) {
$args[] = array_shift($vars);
} elseif (0 == $type && isset($vars[$name])) {
$args[] = $vars[$name];
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw new \Exception('method param miss:' . $name);
}
}
return $args;
}
}

Comment ( 0 )

Sign in for post a comment

PHP
1
https://gitee.com/zhimiao/frame-php.git
git@gitee.com:zhimiao/frame-php.git
zhimiao
frame-php
frame-php
master

Search

103611 48b8ff67 1899542 103622 4d02230c 1899542