igniphp/reflection-api

1.0.2 2018-05-14 13:35 UTC

This package is not auto-updated.

Last update: 2024-09-18 03:58:12 UTC


README

Build Status Scrutinizer Code Quality Code Coverage

安装

composer require igniphp/reflection-api

反射API

许可协议:MIT许可

Reflection api 提供了允许以下操作的工具:

  • 读取和写入对象的属性
  • 在运行时构建类
  • 检索闭包体
  • 不使用反射API实例化对象

读取对象的属性

use Igni\Utils\ReflectionApi;

class TestClass
{
    private $test;
    
    public function __construct()
    {
        $this->test = 1;
    }
}

$instance = new TestClass();

ReflectionApi::readProperty($instance, 'test');

写入对象的属性

use Igni\Utils\ReflectionApi;

class TestClass
{
    private $test;
    
    public function __construct()
    {
        $this->test = 1;
    }
}

$instance = new TestClass();

ReflectionApi::writeProperty($instance, 'test', 2);

创建实例

use Igni\Utils\ReflectionApi;

class TestClass
{
    private $test;
    
    public function __construct()
    {
        $this->test = 1;
    }
}

$instance = ReflectionApi::createInstance(TestClass::class);

在运行时构建和加载类

use Igni\Utils\ReflectionApi;
use Igni\Utils\ReflectionApi\RuntimeProperty;
use Igni\Utils\ReflectionApi\RuntimeMethod;

$class = ReflectionApi::createClass('TestClass');

$class->addProperty((new RuntimeProperty('test))->makePrivate());

$constructor = new RuntimeMethod('__construct');
$constructor->addBody(
    '$this->test = 1'
);

$getTest = new RuntimeMethod('getTest');
$getTest->setReturnType('string');
$getTest->addBody(
    'return $this->test'
);

$class->addMethod($constructor);
$class->addMethod($getTest);

$class->load();

$instance = $class->createInstance();

$instance instanceof 'TestClass';// true.
$instance->getTest();// 1