I understand that global variables should be avoided generally. As a beginner, I’m trying to understand whether making a $view variable global in a dynamic web program built following MVC principles is one of those cases where globals are a good idea.
In my program, I create the $view (as an object that contains an empty array) in index.php, and turn it into a global in the controllers that use it.
Thanks!
JDelage
Why? If you controller needs the
$viewthen just pass it in via the constructor or a setter. Dependencies on Globals can always be resolved by using Dependency Injection.Also, please reconsider if the View should be just an array. The View has to be rendered at some point. Rendering is a responsibility I’d see on the View. An array cannot render itself, so I assume you are doing it elsewhere. That would be a violation of the Single Responsibility Principle. I’d rather do something along the lines of (simplified):