开发者

Accessing a global variable inside nested functions

Here's my scenario:

$foo = bar;

one()
{
   two()
   {
      three()
      {
  开发者_JAVA技巧       // need access to $foo here
      }
   }
}

I know I could pass $foo down all three functions, but that isn't really ideal, because you may or may not require it, besides, there are other parameters already and I don't want to add to that list if I can prevent it. It's only when you get to three() do you need $foo. I know I could also specify global $foo; in three(), but I read that this wasn't a good practice.

Is there another way $foo can be made available to three() without doing either of those?

To provide a little more info, $foo in this case is info on how to connect to the database e.g. server, user, pass, but only in three() does it actually need that info. Of course I could connect to the database right as the document loads, but that feels unecessary if the document might not need it.

Any ideas?

UPDATE: I'm sorry, I didn't mean to have "function" at the beginning of each function implying that I was created them in a nested way.


Yes, you can use global, or pass it through as a parameter. Both are fair ways. However, I'd do the latter. Or, you can also use closures and the use keyword:

$foo = 'bar';

$one = function() use($foo) {
   $two = function() use($foo) {
      $three = function () use($foo) {
         // access to $foo here
      };
   };
};

Can also be use(&$foo) if you need to modify the top $foo's value inside of $three()


Using global is not a bad practice if used properly. This case you would use global and it will be totally fine.

Since global makes functions get access to global variables, there are data corruption risks. Just make sure to use with caution and you know what you're doing (i.e. not accidentally change the data that you don't want it to change. This sometimes causes some nasty bugs that's hard to track.)

Summarize: global in this case is perfectly fine.

What's really bad is nested functions, at least in PHP.


Don't listen anybody, who are speaking about global.
Read books about OOP (e.g. this one), read about Dependency Injection, Factory-patterns.
Dependency Injection is the best way to create flexible and easy-to-maintain code, and by DI philosophy you will pass $foo from first to third function in arguments, or will pass Context object with all necessary variables (if you want to minimize count of arguments).
More about DI you can read here: http://components.symfony-project.org/dependency-injection/trunk/book/00-Introduction

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜