Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use a variable defined in one php file, in another php file

Tags:

php

I have defined a variable $month is "water_sources.php" file. Can I use this variable in another file "add_month.php" If yes then please suggest how?

like image 419
Harsh Avatar asked Jun 01 '11 17:06

Harsh


2 Answers

Simple answer is yes. Take a look at the docs for include: http://php.net/manual/en/function.include.php, require: http://php.net/manual/en/function.require.php, and require_once: http://php.net/manual/en/function.require-once.php. Which you use will depend on whether the file is... you guessed it, required. :)

Luckily, the mechanics for using each are identical. In the sample code below, you could interchange require or require_once for include and the demo will still function correctly. Try to create the files and use each of the functions. Then, delete the vars.php file and try your tests again. Notice that your script will fail if you use require and the included file does not exist.

vars.php

<?php

$color = 'green'; $fruit = 'apple';

?>

test.php

<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>
like image 146
Chris Baker Avatar answered Sep 29 '22 09:09

Chris Baker


Yes you can. Just use the require or require_once commands to pull in the other php file. Like this:

require_once('water_sources.php');
echo "Month is $month\n";
like image 39
Chris Eberle Avatar answered Sep 29 '22 09:09

Chris Eberle