PHP code example of igniphp / reflection-api

1. Go to this page and download the library: Download igniphp/reflection-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

igniphp / reflection-api example snippets


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