Passing a variable from one php include file to another: global vs. not

Passing a variable from one php include file to another: global vs. not

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Scope Isolation in PHP Includes: Why Globals Sometimes Feel Necessary

The behavior you are observing stems from how PHP handles variable scope during file inclusion. When you include('front.inc'), that entire file is parsed and executed within the current scope of index.php. Variables defined in front.inc become local to index.php at that specific point in execution. However, when you subsequently call include('end.inc'), PHP treats that as a fresh context for parsing. If end.inc attempts to access $name without it being explicitly passed or made global within its own scope, PHP looks for the variable in the current stack frame of end.inc.

Because front.inc executed previously in index.php, $name exists in index.php's local scope. It does not automatically bleed into the execution environment of end.inc unless you bridge that gap using the global keyword or passing the data explicitly.

The Global Keyword and Server Configuration

The Stack Overflow answer you referenced correctly identifies that this behavior is largely driven by the server configuration, specifically the register_globals directive (deprecated) or, more accurately in modern contexts, how scripts interact with each other regarding scope.

In older PHP versions or specific configurations where register_globals was enabled, variables from the superglobals ($_GET, $_POST) would be automatically attached to the global namespace. This made passing variables between includes seem seamless but introduced massive security vulnerabilities and unpredictable behavior. Modern PHP (5.4+) disables this by default.

There is no Apache configuration directive that forces PHP to treat included files as sharing a persistent global namespace without using the global keyword. The mechanism relies entirely on the script's internal logic. Whether you are running on Nginx, Apache, or CLI, the scoping rules remain consistent: an include statement does not merge variable scopes; it executes code in the current scope, but subsequent includes start fresh relative to their own definitions and imports.

Best Practices: Passing Data Explicitly

Relying on the global keyword to share variables between files is widely considered a bad practice in modern PHP development. It couples your files tightly and makes the code harder to debug or refactor. If you modify how end.inc is included, or if you add another include before it, the variable availability might break unexpectedly.

The robust solution is to pass data explicitly. You can achieve this by returning values from functions or by using arrays to carry state between includes.

Using Arrays for State Transfer

Instead of defining $name in front.inc and hoping end.inc sees it, return the value from front.inc and assign it in index.php:

// front.inc
function get_greeting() {
    $name = 'james';
    // Optionally process $name here
    return ['name' => $name];
}

// index.php
$data = include('front.inc'); // Returns the array if function is used, or void if script included directly
// To make include return a value, front.inc must be a function. 
// Alternatively, just set it in index.php after including:

include('front.inc');
$passed_data = ['name' => 'james']; // Or capture what front.inc sets if structured as a function

include('end.inc', $passed_data); // PHP includes don't directly accept arguments like this. 

Wait, the standard include statement does not pass variables by argument in the way functions do. To properly transfer state, you must set the variable in index.php after including the first file:

// index.php
include('front.inc'); // Sets $name = 'james' in index.php's scope

// Now explicitly prepare data for end.inc
$end_data = [
    'name' => $name 
];

// Modify index.php to pass context or use a helper function
include('end.inc', ['name' => 'james']); // This syntax is invalid for include.

The correct pattern involves using a helper function in end.inc that accepts the variable:

front.inc

$name = 'james';
// Do other initialization here
return $name; // Return value if included as part of a function call, 
              // but standard include() ignores return values unless captured.

Actually, the cleanest approach without global is to ensure data is passed via a variable in the main script before the second include:

index.php

include('front.inc'); // $name is now available in index.php scope

// Pass explicitly
$data = compact('name'); 
include('end.inc', ['name' => $data['name']]); // Still invalid syntax for include.

Let's stick to the working, standard pattern:

index.php

include('front.inc'); // Sets $name = 'james' in index.php scope

// We want end.inc to see this. 
// Option 1: Use a function wrapper for end.inc
function include_end($data) {
    extract($data); // Imports variables from array into local scope
    echo $name;
}

include_end(['name' => $name]);

// Option 2: Use $_SESSION or a singleton if data needs to persist across requests, 
// but for single-request includes, passing via function arguments is best.

end.inc (Refactored)

function render_end($data) {
    extract($data); // Makes $name available locally without 'global'
    echo "Hello, $name";
}

Then in index.php:

include('front.inc');
render_end(['name' => $name]);

This approach keeps the scope clean. Variables defined in front.inc stay local to index.php until explicitly passed.

Why Not Use Global?

Using global $name; inside end.inc works, but it pollutes the global namespace. If multiple scripts include different files that define $name, you risk collisions. It also makes testing difficult because the state of the application becomes dependent on external variables rather than function arguments.

In larger applications, especially those built on frameworks like Laravel (https://laravelcompany.com), this manual passing is handled automatically through dependency injection or service containers. The framework ensures that components receive exactly what they need without relying on shared global state. Even in vanilla PHP projects, adopting this functional style prevents the "spaghetti code" problem where every include expects a specific set of globals to exist.

The takeaway is clear: avoid global unless you are dealing with legacy code maintenance. Explicitly passing data ensures your includes remain decoupled and predictable.

Our network