PHP code example of bentools / reflection-plus

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

    

bentools / reflection-plus example snippets


use BenTools\ReflectionPlus\Reflection;

// From a class name
$reflectionClass = Reflection::class(MyClass::class);

// Or from an object
$object = new MyClass();
$reflectionClass = Reflection::class($object);

// From a class name
$reflectionProperty = Reflection::property(MyClass::class, 'someProperty');

// Or from an object
$object = new MyClass();
$reflectionProperty = Reflection::property($object, 'someProperty');

// From a class name
$reflectionMethod = Reflection::method(MyClass::class, 'someMethod');

// Or from an object
$object = new MyClass();
$reflectionMethod = Reflection::method($object, 'someMethod');

// Get a reflection property
$reflectionProperty = Reflection::property($myClass, 'myProperty');

// Get all class types that can be set to this property
$classTypes = Reflection::getSettableClassTypes($reflectionProperty);

// Returns an array of fully qualified class names
// that are compatible with the property type
// and are instantiable (no interfaces or abstract classes)

$reflectionProperty = Reflection::property($myClass, 'myProperty');

// Check if a particular class is compatible
$isCompatible = Reflection::isPropertyCompatible($reflectionProperty, SomeClass::class);

// Returns true if SomeClass can be assigned to the property

$reflectionProperty = Reflection::property($myClass, 'myProperty');
$classNames = [ClassA::class, ClassB::class, ClassC::class];

// Find the first compatible class in the array
$bestClass = Reflection::getBestClassForProperty($reflectionProperty, $classNames);

// Returns the class name of the first compatible class
// or throws InvalidArgumentException if none are compatible

$reflectionProperty = Reflection::property($myClass, 'myProperty');
$type = $reflectionProperty->getType();

// Check if a class is compatible with this type
$isCompatible = Reflection::isTypeCompatible($type, SomeClass::class);

// Works with:
// - ReflectionNamedType (standard class or primitive types)
// - ReflectionUnionType (Type1|Type2)
// - ReflectionIntersectionType (Type1&Type2)

// For a property like: public ClassA|ClassB $property;

$reflectionProperty = Reflection::property($class, 'property');
$classTypes = Reflection::getSettableClassTypes($reflectionProperty);

// $classTypes will contain [ClassA::class, ClassB::class] if both are instantiable

// For a property like: public ClassA&InterfaceB $property;

$reflectionProperty = Reflection::property($class, 'property');

// You can check if a specific class meets all