Access a global variable in a PHP function

前端 未结 9 1989
感动是毒
感动是毒 2020-11-29 05:33

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn\'t this code work?



        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-29 06:08

    You can do one of the following:

    Or

    That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).

提交回复
热议问题