2

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 so:

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

1 Answer 1

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

Or return an array that contains all the values you want to "export".
thanks guys, I changed the function to just return the file instead of the whole include statement, easy solution - just how I like it :)
For completeness, some other excellent suggestions (and code samples) are given in answer to this question: stackoverflow.com/questions/4525310/alias-to-include

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.