Reducing Dynamic PHP Code
<?php $controller->$action(); ?>
Seven characters, and the static analysers give up. They can’t tell whether $action is list, show, or dropDatabase. It might assume the worst, but more often, it assumes nothing and says nothing: this is going to fail at execution time, when we get hard data. The call is in the code, the method is in the code, and the link between them is under the control of whoever is sending the action variable. By design.
This is dynamic coding, where part of the source code is found among the data that are sent to the controller. It is very powerful, and, at times, confusing and difficult to update. PHP is known for its dynamic code features.
The land where everything is named
One end of the spectrum is the code where every name is hard coded:
<?php $controller->list(); ?>
Then, static tools read this, follow list() to its definition, checks the signature, renames it when the method has to be renamed, and tells you when it no longer exists. Nothing is guessed, because nothing is computed. Static code is nice for static analysis, and this is the reference point: every dynamic call is a place where the tool has lost that information, and the rest of this piece is about getting some of it back. There are entire languages that are built around that safety feature.
Dynamic code, everywhere!
On the other end is the code that simplifies everything:
<?php $action = $_GET['action']; $controller->$action(); ?>
Here the value is as random as it gets. Indeed, anyone with a browser controls it. Yet PHP does not let it call just anything. The engine checks the name before it runs: the method must be a valid name, it must also exist, and its visibility must be accessible from the calling scope. A private or protected method is refused, and so is a name that does not exist or is an array, which raises an Error. So the values that can actually do something are the public methods of $controller.
So, on second thought, that set is actually finite: it is set by the class definition. In the end, it is a whitelist, even though nobody wrote it down.
There is one way to switch that guard off. When the class defines __call(), every name is accepted and forwarded to it, and the engine stops checking anything at the first call:
<?php
final class LoggedOrders
{
public function __construct(private Orders $inner) {}
public function __call(string $name, array $args): mixed
{
return $this->inner->$name(...$args);
}
}
?>
Nothing in the wrapper knows the actual method names. So, the real whitelist is the interface Orders implements, and the wrapper exposes it. Nothing says so, and the relay adds an extra layer of abstraction. When Orders loses a method, the wrapper keeps compiling and fails only when someone calls the missing method through it. Declaring the interface and writing out each forwarded method turns that list back into something the engine can check.
Between the fully static and dynamic code: the partially known whitelists
Most real code sits between these extremes. The set of allowed values is known to the program, sometimes even to the developer, but not in a form a tool can easily access. In fact, there are four situations that come back again and again. For each one, the whitelist exists; the question is how far it is in the code, and how we could pull it into the code and into the limelight.
Whitelisted, but written as a literal
The most common case is an array of allowed values, sitting in a condition:
<?php
$action = $_GET['action'] ?? 'list';
if (in_array($action, ['list', 'show', 'delete'], true)) {
$controller->$action();
}
?>
The set is known and hard coded, which is more than the initial illustration. But it is written as data inside a test, not as a declaration with high priority. An analyser still sees $controller->$action() and learns nothing from the array, because the array is a condition, not a type. And the array may actually be stored in a file, far far away. Three months later, someone adds 'export' to the array, forgets that only the class ExportController has a method called export(), on another branch, and nothing notices it until a user does.
The intermediate solution is to give the list a name, as an enumeration with string values:
<?php
enum Action: string
{
case List = 'list';
case Show = 'show';
case Delete = 'delete';
}
?>
It is the same list, and now it is a type. It can be passed around, documented, and checked. Turning the request string into a case is one call, Action::tryFrom(), which returns null for anything that is not on the list. From there, a match names each method, and the dynamic call goes away:
<?php
match (Action::tryFrom($_GET['action'] ?? '') ?? Action::List) {
Action::List => $controller->list(),
Action::Show => $controller->show(),
Action::Delete => $controller->delete(),
};
?>
Adding Export to the enum without a branch is now a visible gap instead of a silent one. This refactoring works best when the list of strings is a golden standard that must be written by hand. The list might be quite long, and stay efficient: the strongest limitation is actually the amount of code that has to be written.
Checked with property_exists()
The second case is a hydrator that checks each name at the last moment:
<?php
foreach ($data as $key => $value) {
if (property_exists($this, $key)) {
$this->$key = $value;
}
}
?>
The whitelist is the set of properties the class declares, and the check happens at runtime. No function returns that set in the form the check needs. The only way to list the properties is Reflection: ReflectionClass::getProperties(), a filter on visibility, a loop, and a set to compare against. Compared to a single property_exists(), that is a long detour, so nobody writes it, and the list never gets collected. And, in the end, property_exists() is still checking properties against a list, like in_array(), even if the list is not visible.
Here, the intermediate solution is to generate an enum from the class’s properties. A build step runs Reflection once, writes the enum to a file, and the check becomes a lookup:
<?php
// generated from Invoice, do not edit
enum InvoiceField: string
{
case Customer = 'customer';
case Total = 'total';
}
foreach ($data as $key => $value) {
if ($field = InvoiceField::tryFrom($key)) {
$this->{$field->value} = $value;
}
}
?>
The reflection cost is paid once, at build or development time, and the result is a file a tool can read. There is one trap. property_exists() returns true for private properties too, so the generator has to decide which properties the write is allowed to touch and include only those. Otherwise the enum lists the names the check would accept, not the names the code should accept.
Checked with class_exists()
The third case is an exporter that checks for a class before using it:
<?php
$class = 'App\\Exporter\\' . ucfirst($format);
if (class_exists($class)) {
$exporter = new $class();
}
?>
The whitelist is the contents of src/Exporter/, which is an autoloader check, or a read on the disk. It is harder to collect than a property list on a known class, because the candidates are built from a string. ucfirst() does not help, and the case sensitivity of the local file system may be a source of extra traps. A tool could read the autoload map in composer.json and list the candidates, but that list is not in the code. Nor can it be there without a long detour.
The intermediate solution is a generated map from format to class, the same idea as the enum:
<?php
// generated from src/Exporter/, do not edit
final class Exporters
{
private const FORMATS = [
'csv' => CsvExporter::class,
'json' => JsonExporter::class,
];
public static function for(string $format): Exporter
{
$class = self::FORMATS[$format] ?? throw new UnknownFormat($format);
return new $class();
}
}
?>
This goes against the grain of PHP. The language is built around dynamic inclusion: you name a class, and the autoloader finds it when it is needed. A generated list reverses that, naming every class up front, and the build step has to keep it in sync with the disk. The compensation is that ::class does not trigger autoloading. The map holds the names without loading the classes, so the lazy behaviour survives. What changes is that the candidates live in one place. A rename of CsvExporter now breaks the map at build time, instead of making class_exists() quietly return false in production.
Static arrays
The last case of dynamic code is an array whose keys are written out one by one, with nothing computed:
<?php
function productRow(array $row): array
{
return [
'name' => $row['name'],
'price' => (float) $row['price'],
];
}
?>
The keys of this array are known before the program runs. A tool can read the literal and collect them without executing anything, which is more than the hydrator offered. The gap is that the producer and the consumers of this array live in different files, and nothing connects them. A consumer that reads $row[$field] with a field chosen at runtime is checking a key nobody has declared.
The intermediate solution is to declare the shape, in a docblock that static analysers read:
<?php
/** @return array{name: string, price: float} */
function productRow(array $row): array
?>
This is not native PHP. It is a convention that tools such as PHPStan and Psalm understand and the engine ignores. It does not change what the code does, but it makes the set of keys a fact the tool can check at every read.
One simple option is to make the array a class: even with a set of public properties and no methods, this class is now carrying the definition and types for each entry. It may be converted easily into an array with a simple (array) cast, and it may also be hydrated with a clever usage of promoted properties.
<?php
class ProductRowEntity {
function __construct(public string $name,
public float $price,
) {}
}
function productRow(array $row): array
{
// No need to update 'name' here,
$row['price'] = (float) $row['price'];
return (array) new ProductRowEntity(...$row);
}
?>
Dynamic, but over a known set
Note what did not change in these examples. The program still decides at runtime which exporter to build, which method to call, and which property to write. The reduction did not remove the dynamics; it removed the unknown part of it. The set of possible values was always finite: sometimes large, but always finite. My personal experience is a world record of 1342 methods in a god class. Before, it was implicit, spread across an in_array, a property list, a directory of files, and the keys of an array. After, it is written in one place per case, where an automated tool can read it.
This distinction matters for an audit. A dynamic call whose possible values can be enumerated is a call that can be audited: you can check each candidate, and say that the code is safe for all of them. A dynamic call whose values come from a database row, an HTTP parameter, or a computed string is a call that cannot be covered by reading the code at all, nor by listing all of them. It is not necessarily dangerous, but it opens the door to a cascade of small errors that may ultimately lead to a major problem.
So the useful question, when looking at a dynamic call, is not “should I remove it?” It is “how can I build a set for validation?” If the answer is yes, write the set down, and the call becomes checkable even though it stays dynamic. If the answer is no, the call is the real problem, and it deserves a comment, a guard, or a rewrite.
The bigger picture
A lot of whitelists that dynamic PHP relies on are not hidden. They are in the in_array literals, the declared properties, the directory of class files, and the keys of the arrays the program builds. A tool that walked the code could collect them all, and say, for each dynamic site, how many values it can resolve and which ones it cannot.
That tool does not really exist in the form I would want. Pieces of it exist in various static analysers, and enough of the reduction can be done by hand that it is worth doing now, whatever the tooling. But the result of the exercise is a question that a static analyser would have to answer for the whole codebase: of all the dynamic calls in your application, how many have a whitelist that someone wrote down, and how many depend on a set that only exists in production data?
Dynamic code doesn’t have to be demonized as bluntly as it is now. We do need a few more accessible validation lists to make all these calls safer, and easier to read at the calling site. And the ultimate one is new $classname. How can I constrain it to a short list of acceptable classes, beyond a mere namespace?

