How to use php variables from an included php file
Solution 1
They should just roll over:
File1.php
<?php
$var1 = "TEST";
?>
File2.php
<?php
include("File1.php");
echo $var1; //Outputs TEST
?>
Solution 2
Have you actually tried it?
Just use the variables. They are available within the scope of the including file.
From the PHP manual:
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.
Solution 3
When you include one file in another, everything is visible from both of them. Imagine them as having one file, so you use the variables the regular way - by typing their name out.
dave
Updated on April 07, 2020Comments
-
dave about 4 years
I have these variables that are set in one php file, and when i include that php file in another php file, how do i use those variables from the included php file?
-
eisberg about 13 yearsA better question will be: how to not use php varialbes from an included php file ;-)
-
Francisco Corrales Morales over 9 yearswhy not use
define('var', 'value');
? -
Jess over 9 yearsNot sure what you mean. Define is used to create constants. Constants will also carryover between files, but the question was about variables, which is why I used one in my example.
-
Francisco Corrales Morales over 9 yearsif I use
define
I don't have to useinclude
norrequire
? -
Jess over 9 years@FranciscoCorralesMorales Still not sure what you're asking. You'd still need to use require/include. the define statement would take place of the assignment statement on the second line of the first file and would be
define('VAR1', 'TEST')
. Then in the second file the echo statement would beecho VAR1; // Still outputs TEST
. -
mikewasmike almost 9 yearsmake sure you do not use include_once, it kind of hides variable.
-
Jess almost 9 years@mikewasmike I don't believe that is the case. The only difference between include and include_once is include_once includes, well, once. It keeps track of all files it includes, and if the function gets called more than once for the same file it just does nothing. Is that what you mean? On subsequent calls
include_once 'File1.php'
wouldn't do anything? -
user25 over 7 yearsdoesn't work if I use
get_header();
(wordpress) instead ofinclude