Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a php file index.php and its url is index.php?var=item I defined get variable in index.php

in index.php

<?php
    require "included.php";
    $var=$_GET['var'];
?>

I echoed this variable in my included.php like below

in included.php

<?php
    echo $var;
?>

When I launch index.php?var=item, its shows an error that var is not defined in included.php?

How to overcome this? I want to define some variables in index.php from url and do some staff in included file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

like Joachim Martinsen posted as a comment (I don't know why he hasn't just answered), you have to set the $var before including your file:

<?php
    $var=$_GET['var'];
    require "included.php";
?>

inlcuding in PHP basically just works like concatenating one file out of other files. so your original code would result in:

<?php
    echo $var;
    $var=$_GET['var']; 
?>

which obviously doesn't work because the variable is echoed before it is getting a value assigned.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...