PHP pass variable to include PHP pass variable to include php php

PHP pass variable to include


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>


Option 3 is impossible - you'd get the rendered output of the .php file, exactly as you would if you hit that url in your browser. If you got raw PHP code instead (as you'd like), then ALL of your site's source code would be exposed, which is generally not a good thing.

Option 2 doesn't make much sense - you'd be hiding the variable in a function, and be subject to PHP's variable scope. You'ld also have to have $var = passvariable() somewhere to get that 'inside' variable to the 'outside', and you're back to square one.

option 1 is the most practical. include() will basically slurp in the specified file and execute it right there, as if the code in the file was literally part of the parent page. It does look like a global variable, which most people here frown on, but by PHP's parsing semantics, these two are identical:

$x = 'foo';include('bar.php');

and

$x = 'foo';// contents of bar.php pasted here


Considering that an include statment in php at the most basic level takes the code from a file and pastes it into where you called it and the fact that the manual on include states the following:

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.

These things make me think that there is a diffrent problem alltogether. Also Option number 3 will never work because you're not redirecting to second.php you're just including it and option number 2 is just a weird work around. The most basic example of the include statment in php is:

vars.php<?php$color = 'green';$fruit = 'apple';?>test.php<?phpecho "A $color $fruit"; // Ainclude 'vars.php';echo "A $color $fruit"; // A green apple?>

Considering that option number one is the closest to this example (even though more complicated then it should be) and it's not working, its making me think that you made a mistake in the include statement (the wrong path relative to the root or a similar issue).