0

In my script, I choose which page to include based on a variable.

Does the included page receive the variables that are defined in the main page? Or so I have to redefine them?

If so, what's the best way to pass the variables to the included page?

I tried include("page.php?var=".$var)

But it seems that actually tries to include a file with that string name.

Advice?

hakre
  • 193,403
  • 52
  • 435
  • 836
JYuk
  • 5
  • 3
  • 2
    Please read about the function first. All your questions should be covered: http://php.net/include. Keep an eye on *variable scope* if you have no time to read. – hakre Sep 26 '12 at 11:31

6 Answers6

0

Variables that are already in scope in the first page are already defined in the second.

MidnightLightning
  • 6,715
  • 5
  • 44
  • 68
0

You are better off setting the variables themselves in the main page. include tries to include a local file, not a HTTP GET request, but just set the variables anyway and you can use them.

Amelia
  • 2,967
  • 2
  • 24
  • 39
0

If you define $var = 1 and after that include("page.php"); the variable will be accessible in that file, since it's nothing more then an extension of what you already got.

Peon
  • 7,902
  • 7
  • 59
  • 100
0

This ... "include("page.php?var=".$var)" won't work

Instead try the following:

page1.php

<?php

$dog_name = "scruff";

include("otherpage.php");

?>

otherpage.php

<?php

echo $dog_name;

?>

This will output on page1.php:

scruff

As midnightlightning said: "Variables that are already in scope in the first page are already defined in the second."

Community
  • 1
  • 1
Chris
  • 5,516
  • 1
  • 26
  • 30
0

If you define you variable before include page, you don't need any query string. Your variable will be accessed in the included page with just name. for example

$name = "Awais"
include("page.php");

then in page.php

 echo $name; //will print Awais
Awais Qarni
  • 17,492
  • 24
  • 75
  • 137
0

Does the included page receive the variables that are defined in the main page?

Yes, the code you include is within the same scope. That is also the documented behaviour, see include.

$var = 'value';
include('page.php'); # has $var defined now.
unset($var);
include('page.php'); # has $var undefined now.

So as you can see, there is no need to redfine them.

But you might want to separate that because it has side-effects, see:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836