PHP code example of crowdstar / reflection

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

    

crowdstar / reflection example snippets




declare(strict_types=1);

tion;

class Helper
{
    private string $key;

    private static string $keyStatic;

    private function get(): string
    {
        return 'Private method invoked.';
    }

    private static function getStatic(int $i, int $j): string
    {
        return "Private static method invoked with parameter {$i} and {$j}.";
    }
}

$helper = new Helper();

// Access properties and invoke methods from objects.
Reflection::setProperty($helper, 'key', 'Set value to a private property.');
echo "Output 1: ", Reflection::getProperty($helper, 'key'), PHP_EOL;
echo "Output 2: ", Reflection::callMethod($helper, 'get'), PHP_EOL, PHP_EOL;

// Access static properties and invoke static methods from objects.
Reflection::setProperty($helper, 'keyStatic', 'Set value to a private static property.');
echo "Output 3: ", Reflection::getProperty($helper, 'keyStatic'), PHP_EOL;
echo "Output 4: ", Reflection::callMethod($helper, 'getStatic', [1, 2]), PHP_EOL, PHP_EOL;

// Static properties and methods can also be accessed/invoked from a class directly.
Reflection::setProperty(Helper::class, 'keyStatic', 'Set another value to a private static property.');
echo "Output 5: ", Reflection::getProperty(Helper::class, 'keyStatic'), PHP_EOL;
echo "Output 6: ", Reflection::callMethod(Helper::class, 'getStatic', [3, 4]), PHP_EOL;