Why is it considered bad practice to use “global” reference inside functions? [duplicate]

末鹿安然 提交于 2019-11-26 23:17:29

I think a top reason for avoiding this is that it hides dependencies.

Your functions get_data and run_html do not advertise in any way that they share data, and yet they do, in a big way. And there is no way (short of reading the code) to know that run_html will be useless if get_data has not been called.

As the complexity of your codebase grows, this kind of lurking dependency will make your code fragile and hard to reason about.

Because global variables can be modified by the process without other parts of your code knowing it producing unexpected results.

You should always try to keep variables scoped as locally as possible -- not only will this help you with debugging, but it will keep your code easier and cleaner to read and go back and modify.

If you are looking to share data across multiple functions, you might look into making a class for your data and then defining methods to operate on the data encapsulated in your object. (Object-Oriented programming)

For many reasons, for example:

  • Hard to support code with global variables. You don't know where global variables can affect your logic and don't control access to them

  • Security - if you have complex system (especially with plugins), someone can compromise all system with global variables.

Settings in a global variable are fine, but putting data that can be modified into a global variable can, as tkone said, have unexpected results.

That said, I don't agree with the notion that global variables should be avoided at all costs - just try wrapping them into, say, a singleton settings class.

It is bad practice to use variables from a different scope to your own, because it makes your code less portable. In other words, if I want to use the get_data() function somewhere else, in another project, I have to define the $DATA_PAGE variable before I can use it.

AFAIK this is the only reason this should be avoided - but it's a pretty good reason.

I would pass by reference instead.

function get_data (&$data_page, $page_name )
{
  $data_page['temp'] = 'template';
  $data_page['title'] = 'test page';
  [...]
}
get_data($DATA_PAGE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!