Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, getting variable from another php-file

Tags:

php

So I wonder if it is possible to get a variable from a specific php-file when the variable-name is used in multiple php-file. An example is this:

<header>  <title>   <?php echo $var1; ?>  </title> </header> 

page1.php has $var1 = 'page1' page2.php has $var1 = 'page2'

footer.php should have <a href="">$var1 from page1</a><a href="">$var1 from page2</a>

Ok the example is a bit abstract, but as short as I can make it. I think you get what I am getting at! So it is the in the footer I am after! Got any solutions?

like image 415
Carl Papworth Avatar asked Oct 30 '12 08:10

Carl Papworth


People also ask

What is difference between require and include in PHP?

The require() function will stop the execution of the script when an error occurs. The include() function does not give a fatal error. The include() function is mostly used when the file is not required and the application should continue to execute its process when the file is not found.


1 Answers

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test'; 

mysecondfile.php

$var = 'tester'; 

test.php

include 'myfile.php'; echo $var;  include 'mysecondfile.php'; echo $var; 

Output:

test

tester

I suggest using different variable names.

like image 86
Wayne Whitty Avatar answered Oct 02 '22 14:10

Wayne Whitty