开发者

PHP variable scope with nested include returned by function

Thanks in advance for any help. :)

Ok, here's my problem.

Simplified version of the code:

global space with include file

include file where $var is defined and function is called that returns an include statement

include file returned by function and where $var is no longer accessible

Why is $var no longer accessible?

I suspect it has to do with the function or maybe I am missing something else. The function is like s开发者_开发问答o:

function blah() {
return include_once 'filename.php';
}


Works as designed. Think of the code as if the includes weren't there: You're inside a function, which has its own scope. Global variables are not accessible there.

Your options:

  • Pass the variable as a reference to blah(&$variable)

  • Import the variable from global space using global $varname

  • If you're on PHP 5.3, use the new closure feature

  • Use a fancy OOP construct like Static classes, Singletons or Dependency Injection (probably overkill)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜