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

I defined the $ month variable - the file "water_sources.php". Can I use this variable in another add_month.php file. If so, suggest how?

+4
source share
4 answers

Yes, you can. Just use require or require_once commands to pull out another php file. Like this:

 require_once('water_sources.php'); echo "Month is $month\n"; 
+7
source

The 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 . What you use will depend on whether the file is needed ... you guessed it. :)

Fortunately, the mechanics for each of them are identical. In the code example below, you can exchange require or require_once for include , and the demo will still work correctly. Try creating files and using each of the functions. Then delete the vars.php file and retry the tests. Please note that your script will fail if you use require and the attached 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 ?> 
+6
source

If you include the file "water_sources.php", you can reference the variables. See the "scope" link ( http://php.net/manual/en/language.variables.scope.php )

+1
source

just convert the variable to the session variable that you want to use in another php file.

For example, if I created a login page in which I define the username as a variable that will be the same throughout the session. so i will write here

 $_SESSION['username']=$username; 

and use in another php file as you want to display this variable use

 echo '$_SESSION['username']'; 
+1
source

All Articles