PHP: Why is not a good practice using global and what can be used to replace it? -
the answers have read matter have left me more confused anything. instance: if name of variable changed, 1 has change every comparison of variable global inside functions. if pass variable parameter, still have change every comparison.
var $myvar = 5; //this var before $myvariable function myfunc(){ global $myvariable; //it needs changed } function myfunc($mypar){ } var $something = myfunc($myvariable); //it needs changed
renaming isn't primary benefit easier because function , function call in different files. if have global using variable set in different file can confusing quickly. if it's used in single file better approach put function in class , use class property store variable.
class example { private $variable; public function examplemethod() { $this->variable; // instead of global } }
as general rule, try think of each function/method isolated component takes (its parameters) , returns (even if returns void). function internally doesn't matter , gets passed (assuming it's of right type) can determined later. benefit of sort of separation can change individual parts without worrying whole. , once testing globals become problematic.
one more note. if you're using globals configuration, try instead put configuration either class, suggested steini, or can use json file or simple php file returns array. example:
return [ 'setting1' => 'value' ];
Comments
Post a Comment