Why this matters
Global variables make it hard to trace where and how data changes, leading to conflicts and unpredictable behavior. Reducing globals improves encapsulation and testability.
Do not use global variables to share data across your program. Prefer passing values as function parameters or using configuration objects. Limiting variable scope makes code more predictable and less prone to side effects.
Global variables make it hard to trace where and how data changes, leading to conflicts and unpredictable behavior. Reducing globals improves encapsulation and testability.
Side-by-side examples engineers can pattern-match during review.
<?php
// Using a global
$config = [];
function init() {
global \$config;
\$config['debug'] = true;
}
init();
if (\$config['debug']) {
echo 'Debug on';
}
?><?php
// Pass config or use config object\ nfunction initConfig(array \$config): array {
\$config['debug'] = true;
return \$config;
}
\$config = initConfig(['debug' => false]);
if (\$config['debug']) {
echo 'Debug on';
}
?><?php
// Using a global
$config = [];
function init() {
global \$config;
\$config['debug'] = true;
}
init();
if (\$config['debug']) {
echo 'Debug on';
}
?><?php
// Pass config or use config object
function initConfig(array \$config): array {
\$config['debug'] = true;
return \$config;
}
\$config = initConfig(['debug' => false]);
if (\$config['debug']) {
echo 'Debug on';
}
?>From the same buckets as this rule.