PHP pass variable to include

global, global-variables, include, php, variables

Solution

Speaking of passing a variable to include, it doesn't need any special action: any php variable defined prior calling include is already available in the included file (given it's available in the scope where include is called). This is exactly how include works.

While in order to pass a set of variables into a function that calls include inside, you can use extract() Drupal use it, in its `theme()` function.

Here it is a render function with a `$variables` argument.

function includeWithVariables($filePath, $variables = array(), $print = true)
{
    // Extract the variables to a local namespace
    extract($variables);

    // Start output buffering
    ob_start();

    // Include the template file
    include $filePath;

    // End buffering and return its contents
    $output = ob_get_clean();
    if (!$print) {
        return $output;
    }
    echo $output;
}

**./index.php :**

includeWithVariables('header.php', array('title' => 'Header Title'));

./header.php :

<h1><?php echo $title; ?></h1>

Problem

I'm trying to pass a variable into an include file. My host changed PHP version and now whatever solution I try doesn't work. I think I've tried every option I could find. I'm sure it's the simplest thing! The variable needs to be set and evaluated from the calling first file (it's actually `$_SERVER['PHP_SELF']`, and needs to return the path of that file, not the included `second.php`). OPTION ONE In the first file: ``` global $variable; $variable = "apple"; include('second.php'); ``` In the second file: ``` echo $variable; ``` OPTION TWO In the first file: ``` function passvariable(){ $variable = "apple"; return $variable; } passvariable(); ``` OPTION THREE ``` $variable = "apple"; include "myfile.php?var=$variable"; // and I tried with http: and full site address too. $variable = $_GET["var"] echo $variable ``` None of these work for me. PHP version is 5.2.16. What am I missing? Thanks!

Original source