How to pass Global variables to classes in PHP?

后端 未结 5 1545
终归单人心
终归单人心 2021-01-05 02:41

How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = \"         


        
5条回答
  •  执笔经年
    2021-01-05 03:09

    Generally, PHP provides $GLOBAL array, which can be used to access superglobal variables. BTW, using this array is not much better than using "global" statement in the beginning of all your methods. Also, using such approach does not seem to be a good practice for object-oriented code.

    So, you can:

    • either pass these variables as constructor parameter (see answer from ircmaxell for details)

    • or use some configuration class (singleton)

    Decision depends on semantics of your global parameters.

提交回复
热议问题