反射是什么?
它是指在PHP运行状态中,扩展分析PHP程序,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。这种动态获取的信息以及动态调用对象的方法的功能称为反射API。反射是操纵面向对象范型中元模型的API,其功能十分强大,可帮助我们构建复杂,可扩展的应用。
其用途如:自动加载插件,自动生成文档,甚至可用来扩充PHP语言。
PHP反射api由若干类组成,可帮助我们用来访问程序的元数据或者同相关的注释交互。借助反射我们可以获取诸如类实现了那些方法,创建一个类的实例(不同于用new创建),调用一个方法(也不同于常规调用),传递参数,动态调用类的静态方法。
反射api是PHP内建的OOP技术扩展,包括一些类,异常和接口,综合使用他们可用来帮助我们分析其它类,接口,方法,属性,方法和扩展。这些OOP扩展被称为反射。
平常我们用的比较多的是 ReflectionClass类 和 ReflectionMethod类,例如:
class BaseService{
protected static $instance;
/**
* 单例
*/
public static function getInstance()
{
$class_name = get_called_class();
if(!(static::$instance instanceof $class_name)){
static::$instance = new $class_name();
}
return static::$instance;
}
public static function getClassTest($path)
{
$className = new \ReflectionClass($path);
if(!(static::$instance instanceof $className)){
static::$instance = $className->newInstance();
}
return static::$instance;
}
}
class GoodsService extends \frontend\modules\buyer\services\BaseService{
/**
* 测试
* */
public static function getInstance()
{
return parent::getInstance();
}
public function getTest()
{
return 111111;
}
public static function getClassChildTest()
{
$path = get_called_class();
return parent::getClassTest($path);
}
}
namespace frontend\modules\buyer\controllers;
use frontend\modules\buyer\services\GoodsService;
class IndexController extends \frontend\controllers\FrontendBaseController
{
public function actionIndex()
{
echo 'buyer';
}
public function actionTest()
{
$service = GoodsService::getClassChildTest();
echo $service->getTest();
}
}
PHP 反射Reflection
最新推荐文章于 2022-10-31 19:08:06 发布