Last Updated: February 25, 2016
·
1.607K
· jessevondoom

PHP Reflection is your friend

Reflection / introspection is that thing you don't need until you do. And when you do, you generally forget it's there. In a nutshell, reflection allows you to look at a class or a class method and show it's structure to your code.

We use it in two places in the CASH Music codebase, and it's invaluable in both.

First is core framework routing. Ours is a complicated beast with multiple layers of abstraction. The core framework is designed to work with a request/response workflow, and we want it to be as dev-friendly as possible. So to make a call you simple instantiate a new request object, passing it a keyed array containing your parameters, including action type. The action type is matched to a class and function, which is analyzed. The array can contain parameters in any order, and as long as the required parameters are found we can reorder, set defaults, and call the helper function that does all the work.

The second use case is a little more common: documentation. Our docs generator pulls out doc blocks then finds an accurate list of parameters using basic reflection — always up to date and accurate, even when some asshole like me doesn't comment a function all too well.

The basics look a little like this:

$m = new ReflectionMethod($class_name, $method->getName());
$params = $m->getParameters();
foreach ($params as $param) {
    //$param is an instance of ReflectionParameter
    $param->getName(); // parameter name / string
    $param->isOptional(); // optional / bool
}

More on framework routing later. But take a good look at Reflection...in certain situations it's insanely helpful.