Suthan Bala
Suthan Bala

Reputation: 3299

How can I pass the currently defined variables into an included file by a function

I am trying to include a file using a function, and I have several variables defined. I want to access the included file to access the variables, but because I am including it using a function, it is not accessible. The sample scenerio is as follows:

i.e the contents of index is as follows

index.php

<?
...
function include_a_file($num)
{
  if($num == 34)
    include "test.php";
  else
    include "another.php"
}
...
$greeting = "Hello";
include_a_file(3);
...
?>

And the contents of test.php is as follows

test.php

<?
echo $greeting;
?>

The test file is throwing a warning saying the $greeting is not defined.

Upvotes: 1

Views: 63

Answers (2)

Marc B
Marc B

Reputation: 360602

This will not work. include and require act as if the code you're including was literally part of the file at the point the include/require was executed. As such, your external files are going to be in the scope of the include_a_file() function, which means $greeting is OUT OF SCOPE within that function.

You'll have to either pass it in as a parameter, or make it global within the function:

function include_a_file($num, $var) {
                              ^^^^-option #1
   global $greeting; // option #2
}

$greeting = 'hello';
include_a_file(3, $greeting);

Upvotes: 2

Daryl Gill
Daryl Gill

Reputation: 5524

Are you sure your correctly including? And remember PHP is case sensitive:

$Test = "String"; 
$TEst = "String"; 

Both completely different variables..

Furthermore, don't just echo out a variable, wrap it within in a isset condition:

if (isset($greeting)){
 echo $greeting;
} // Will only echo if the variable has been properly set.. 

Or you could use:

if (isset($greeting)){
  echo $greeting;
}else{
  echo "Default Greeting"; 
}

Upvotes: 0

Related Questions