I’m having a bit of trouble understanding includes and function scopes in PHP, and a bit of Googling hasn’t provided successful results. But here is the problem:
This does not work:
function include_a(){
// Just imagine some complicated code
if(isset($_SESSION['language'])){
include 'left_side2.php';
} else {
include 'left_side.php';
}
// More complicated code to determine which file to include
}
function b() {
include_a();
print_r($lang); // Will say that $lang is undefined
}
So essentially, there is an array called $lang in left_side.php and left_side2.php. I want to access it inside b(), but the code setup above will say that $lang is undefined. However, when I copy and paste the exact code in include_a() at the very beginning of b(), it will work fine. But as you can imagine, I do not wish to copy and paste the code in every function that I need it.
How can I alleviate this scope issue and what am I doing wrong?
If the array
$langgets defined inside theinclude_a()function, it is scoped to that function only, even if that function is called insideb(). To access$langinsideb()you need to call it globally.This happens because you
include 'left_side2.php';inside theinclude_a()function. If there are several variables defined inside the includes and you want them to be at global scope, then you will need to define them as such.Inside the
left_side.php, define them as:Then in the function that calls them, try this: