Stop using `global` in PHP

后端 未结 6 2013
醉梦人生
醉梦人生 2020-11-22 03:45

I have a config.php that is included to each page. In config I create an array that looks something like:

$config = array();
$config[\'site_name\         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 04:47

    There is a big discussing between object-oriented and procedural approaches (and more generally, between declarative and imperative ones) and each approach has its upsides and downsides.

    I used 'Config' class that was a Singleton (an OOP version of global). It worked good for me until I had discovered a need to use several of previously-developed solutions together in one application - since all configs were global and referred by the same class (the same variable name, in your case) they conflicted and I had to switch to proper config every time I called code from other sub-application.

    You have two ways:

    a) either design your application in a way you got used to and you are familiar with (that will be better because you already have experience in it and you can predict how long the development will take and what problems may or may not arise); and after you will stuck into limitations of your current approach, refactor to avoid the globals;

    b) look how its done in OOP frameworks (see at least three or four, i.e. Cake, CodeIgniter, Zend, Symfony, Flow3) and either borrow something, or switch to using a framework (or maybe you will be more sure that you do everything right).

提交回复
热议问题