-2

Possible Duplicate:
How to use include within a function?

i have two file

inc.php file

<?php
$var1 = "foo";
$var1 .= "bar";
?>

test.php File

<?php
function getcontent($file) {
 include ($file);
}

getcontent('inc.php');
echo $var1;
?>

When i run test.php it give me error in output

Notice: Undefined variable: var1 in \www\test.php on line 7 

But when i change my test.php file to this

<?php
include ('inc.php');
echo $var1;
?>

its works, and give me output fine

foobar
Community
  • 1
  • 1

3 Answers3

1

When you do it by this

function getcontent($file) {
    include ($file);
}
getcontent('inc.php');

it includes as

function getcontent($file) {
    $var1 = "foo";
    $var1 .= "bar";
}

actually your variables are being included inside the function and not visible outside of the function so the error message occurs.

See this SO answer.

Community
  • 1
  • 1
The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

You have to declare $var1 as global var.

global $var1;

$var1 = "foo";
$var1 .= "bar";

OR

$GLOBALS['var1'] = "foo";
$GLOBALS['var1'] .= "bar";
Marcio Mazzucato
  • 8,841
  • 9
  • 64
  • 79
0

when you include the file in the getcontent function, the vars behave like they were defined there and aren't visible to the outside.

if you declared them as global, it would work.

Stefan S
  • 650
  • 2
  • 10
  • 23