PHP pass variable to include

user1590646 picture user1590646 · Aug 10, 2012 · Viewed 136.5k times · Source

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!

Answer

thi3rry picture thi3rry · Aug 8, 2017

You can use the extract() function
Drupal use it, in its theme() function.

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

function includeWithVariables($filePath, $variables = array(), $print = true)
{
    $output = NULL;
    if(file_exists($filePath)){
        // 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) {
        print $output;
    }
    return $output;

}


./index.php :

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

./header.php :

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