PHP code example of jasny / reflection-factory

1. Go to this page and download the library: Download jasny/reflection-factory 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/ */

    

jasny / reflection-factory example snippets


use Jasny\ReflectionFactory\ReflectionFactory;

$factory = new ReflectionFactory();
$reflection = $factory->reflectClass(\DateTime::class);

use Jasny\ReflectionFactory\ReflectionFactory;

class SomeTool
{
    public function foo(string $class)
    {
        $reflection = new ReflectionClass($class);
        
        return $reflection->getConstant('FOO');
    }
}

class SomeToolTestFooSupport
{
    const FOO = 10;
}

use PHPUnit\Framework\TestCase;

class SomeToolTest extends TestCase
{
    public function testFoo()
    {
        $tool = new SomeTool();
        
        $this->assertEquals(10, $tool->foo("SomeToolTestFooSupport"));
    }
}

use Jasny\ReflectionFactory\ReflectionFactoryInterface;

class SomeTool
{
    protected $reflectionFactory;
    
    public function __construct(ReflectionFactoryInterface $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;    
    }
    
    public function foo(string $class)
    {
        return $this->reflectionFactory->reflectClass($class)->getConstant('FOO');
    }
}

use PHPUnit\Framework\TestCase;
use Jasny\ReflectionFactory\ReflectionFactoryInterface;

class SomeToolTest extends TestCase
{
    public function testFoo()
    {
        $mockReflection = $this->createMock(\ReflectionClass::class);
        $mockReflection->expects($this->once())->method('getConstant')
            ->with('FOO')->willReturn(10);
            
        $mockFactory = $this->createMock(ReflectionFactoryInterface::class);
        $mockFactory->expects($this->once())->method('reflectClass')
            ->with('FakeClass')->willReturn($mockReflection);
            
        $tool = new SomeTool($mockFactory);
        
        $this->assertEquals(10, $tool->foo("FakeClass"));
    }
}