1.2.207. Complex Dynamic Names¶
Avoid using expressions as names for variables or methods.
There are no place for checks or flow control, leading to any rogue value to be used as is. Besides, the expression is often overlooked, and not expected there : this makes the code less readable.
It is recommended to build the name in a separate variable, apply the usual checks for existence and validity, and then use the name. This analysis only accept simple containers, such as variables, properties.
<?php
$a = new foo();
// Code is more readable
$name = strolower($string);
if (!property_exists($a, $name)) {
throw new missingPropertyexception($name);
}
echo $a->$name;
// This is not check
echo $a->{strtolower($string)};
?>
See also Dynamically Access PHP Object Properties with $this.
1.2.207.1. Connex PHP features¶
1.2.207.1.1. Suggestions¶
Extract the expression from the variable syntax, and make it a separate variable.
1.2.207.1.2. Specs¶
Short name |
Variables/ComplexDynamicNames |
Rulesets |
|
Exakat since |
1.8.4 |
PHP Version |
All |
Severity |
Minor |
Time To Fix |
Quick (30 mins) |
Precision |
Very high |
Available in |