PHP global in functions

后端 未结 7 1147
梦谈多话
梦谈多话 2020-11-21 05:41

What is the utility of the global keyword?

Are there any reasons to prefer one method to another?

  • Security?
  • Performance?
  • Anything els
7条回答
  •  [愿得一人]
    2020-11-21 06:04

    The one big reason against global is that it means the function is dependent on another scope. This will get messy very quickly.

    $str1 = 'foo';
    $str2 = 'bar';
    $str3 = exampleConcat();
    

    vs.

    $str = exampleConcat('foo', 'bar');
    

    Requiring $str1 and $str2 to be set up in the calling scope for the function to work means you introduce unnecessary dependencies. You can't rename these variables in this scope anymore without renaming them in the function as well, and thereby also in all other scopes you're using this function. This soon devolves into chaos as you're trying to keep track of your variable names.

    global is a bad pattern even for including global things such as $db resources. There will come the day when you want to rename $db but can't, because your whole application depends on the name.

    Limiting and separating the scope of variables is essential for writing any halfway complex application.

提交回复
热议问题