What is the best practice for accessing global arrays in PHP classes?
When accessing global arrays in PHP classes, it is best practice to use the global keyword within the class method to access the global array. This ensures that the class method can access and modify the global array without any scope issues.
<?php
$globalArray = [1, 2, 3, 4, 5];
class MyClass {
public function accessGlobalArray() {
global $globalArray;
// Access the global array
foreach($globalArray as $value) {
echo $value . " ";
}
}
}
$myClass = new MyClass();
$myClass->accessGlobalArray();
?>