Undefined variable error in PHP include file
Solution 1
mario's got it. Do this:
function phpRocks() {
global $page;
require("includes/dostuff.php");
}
Solution 2
You are including the file inside a function. Therefore the scope of all the included code is the scope of the function. The variable $page
does not exist inside the function. Pass it in:
function phpRocks($page) {
require "includes/dostuff.php";
}
phpRocks($page);
Solution 3
add global var in you function like that
function phpRocks() {
global $page;
require("includes/dostuff.php");
}
Zoolander
Updated on July 05, 2022Comments
-
Zoolander almost 2 years
Possible Duplicate:
Undefined variable problem with PHP functionCan someone tell me why I keep getting undefined variable error messages in my PHP include files?
<?php $page = 1; if (isset($_REQUEST['page'])) { $page = $_REQUEST['page']; } function phpRocks() { require("includes/dostuff.php"); } if ($search) { phpRocks(); } ?>
Then in dostuff.php:
<?php echo $page; ?>
This is the error I'm getting:
Notice: Undefined variable: page in /dostuff.php on line 61Attn down voters/close requesters: Doesn't show any research effort? How so? What else should I have added? I have been stumped over this for a half hour and cannot find any other posts that answer this question. Do I need to be a PHP expert in order to post questions (therefore I wouldn't be posting any questions!)??
-
Gromski over 11 yearsWhy am I the only one here rooting for injection rather than
global
spaghetti? -
Zoolander over 11 yearsThat was just what I needed. Thanks!
-
Mike B over 11 yearsEveryone else put Mario's comment into answer form for the easy reputation. You're the only one who actually added something relevant.
-
zomboble over 11 yearsRead up on scope Zoolander, thats your issue here
-
user428517 over 11 yearsI'm not sure this is the best solution though.
$page
should be a global variable here IMO ... it's a variable created in the global scope which an included file needs to use. The function call doesn't have anything to do with that. Plus he might want to pass "real" arguments to the function in the future, to be used outside ofdostuff.php
. This avoids confusion between the two. -
Gromski over 11 years@sgroves It has everything to do with the function. The function introduces a new scope, which is good. Any values that cross that scope boundary should be explicitly passed in and returned back out. Whatever happens inside the function with those values is irrelevant. It's also irrelevant that the included file "thinks" the variable is global, nothing changes for the included file either way. You're binding the function to surrounding scope it has no influence on. That's code coupling, which should always be avoided.
-
Andrew about 9 yearsvery helpful thanks... this is the best answer
-
Vahid Amiri almost 8 yearsI believe that
global
is a better solution in this case. -
syed mahroof over 4 yearsthanks for great answer