tags:

views:

101

answers:

2

I am wondering if there is a way to pass a variable to a file you are including via include()?

I tried this but got an error:

include("header_alt.php?img=hey");

Is there a way to do that?

Thanks!

+2  A: 

Just define your variable in the first file ; for instance, in temp.php :

<?php
$my_var = 10;

include 'temp-2.php';

die;
?>

And use it in the second file ; temp-2.php :

<?php

var_dump($my_var);

?>

And it should work : I'm getting this output, from temp-2.php :

int 10


The query-string syntax, using stuff like ?img=hey is used when you are requesting some data from a distant server (like when you are using your browser to surf on websites), not when including a file that is on the same server.

Pascal MARTIN
Thanks, for the info. I had been using what you suggested already, just was wondering of a way to make the var only visible from the included page. But ill just continue to do it that same way. Thanks.
John Isaacks
You're welcome :-) Have fun !
Pascal MARTIN
+1  A: 

Smarty provides a really good mechanism for this sort of thing. Plus, using Smarty just makes for better php applications.

http://www.smarty.net/manual/en/language.function.include.php

Variables can be passed to included templates as attributes. Any variables explicitly passed to an included template are only available within the scope of the included file. Attribute variables override current template variables, in the case when they are named the same.

All assigned variable values are restored after the scope of the included template is left. This means you can use all variables from the including template inside the included template. But changes to variables inside the included template are not visible inside the including template after the {include} statement.

Matthew Vines