Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP can't pass variable to included file

I tried to find a solution for this one:

file1.php

$name = "Jacob";
include ("file2.php");

file2.php

Hi there! <?php echo $name ?>

Output

Hi There! Notice: Undefined variable: name in /volume1/web/test/file2.php on line 9 

Need help please ://

like image 758
Luke Avatar asked Dec 05 '22 00:12

Luke


2 Answers

Your code works fine.

If you get that error your file1.php certainly does not define $name in the global scope.

Fyi, quoted from the docs:

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. However, all functions and classes defined in the included file have the global scope.

My testcase with php-5.3.3-pl1-gentoo(cli) in case it's a PHP bug in whatever version you are using - but I doubt that:

[thiefmaster@hades:~]> cat inc1.php
<?php
$name = 'bleh';
include('inc2.php');
?>
[thiefmaster@hades:~]> cat inc2.php
Hi there! <?php echo $name; ?>
[thiefmaster@hades:~]> php inc1.php
Hi there! bleh
like image 101
ThiefMaster Avatar answered Dec 11 '22 12:12

ThiefMaster


Make sure your URL ends in file1.php and not file2.php or some other file that includes file2.php. Also, try reducing both files to exactly what you posted here (plus a <?php at the beginning of file1.php) to rule out surrounding code.

like image 25
phihag Avatar answered Dec 11 '22 12:12

phihag