0

I am a PHP newbie, and I have this question:

say I have:


a.php:

$a = 'foo' ;
$b = 'baz' ;
require ('b.php') ;

How do I pass variables $a and $b to b.php ? How do I use these variables in b.php ?

thanks a lot !!

ajreal
  • 46,720
  • 11
  • 89
  • 119
Yoni
  • 553
  • 3
  • 14
  • 24

2 Answers2

1

You can use these variables straight away in b.php

require(), include(), etc... includes the file in the same scope as the include is made, except for functions/classes that get included in the global scope.

Here's the link to the documentation that explains it nicely : http://php.net/manual/en/function.include.php

Damp
  • 3,328
  • 20
  • 19
1

Just make sure you call require() after setting the variables, and they should be available in b.php.

a.php:

$a = 'foo';
$b = 'baz';
require('b.php');

b.php:

echo 'a: '. $a;
echo 'b: '. $b;
mellamokb
  • 56,094
  • 12
  • 110
  • 136
  • This method does not work. `$a` and `$b` are both undefined in 'b.php'. There is confusion with the require function here. To get the code above working, `$a` and `$b` can remain defined in 'a.php', but then this file needs to be included/required in 'b.php' for the variables to be recognised in the 'b.php' file. Not the other way round, like the above example. – Tom Apr 05 '13 at 18:13