PHP code example of eso / ireflection

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

    

eso / ireflection example snippets





class A { protected $a = 5; protected $b = 10; }
$a = new A();
$refClass = new \ReflectionClass($a);
$propA = $refClass->getProperty('a');
$propB = $refClass->getProperty('b');

$propA->setAccessible(true);
$propB->setAccessible(true);

echo $propA->getValue($a) . "\n"; // prints 5
echo $propB->getValue($a) . "\n"; // prints 10

$propA->setValue($a, 10);
$propB->setValue($a, 20);

echo $propA->getValue($a) . "\n"; // prints 10
echo $propB->getValue($a) . "\n"; // prints 20

class A { protected $a = 5; protected $b = 10; }
$a = new A();
$refClass = ReflClass::create($a);

echo $refClass->getAnyPropertyValue('a') . "\n"; // prints 5
echo $refClass->getAnyPropertyValue('b') . "\n"; // prints 10

$refClass->setAnyPropertiesValues(array('a' => 10, 'b' => 20));

echo $refClass->getAnyPropertyValue('a') . "\n"; // prints 10
echo $refClass->getAnyPropertyValue('b') . "\n"; // prints 20

class A { function sum($a, $b) { return $a + $b; } }
$a = new A();

$method = (new \ReflectionClass($a))->getMethod('sum');
$method->setAccessible(true);
echo $method->invokeArgs($a, array(5, 3)) . "\n"; // prints 8

class A { function sum($a, $b) { return $a + $b; } }
$a = new A();

echo ReflClass::create($a)->invokeAnyMethod('sum', array(10, 3)); // prints 8