Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable error in PHP include file [duplicate]

Possible Duplicate:
Undefined variable problem with PHP function

Can 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 61

Attn 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!)??

like image 818
Zoolander Avatar asked Nov 09 '12 15:11

Zoolander


People also ask

How do I fix undefined variable error in PHP?

Fix Notice: Undefined Variable by using isset() Function This notice occurs when you use any variable in your PHP code, which is not set. Solutions: To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.

How do you fix a undefined variable in a report?

There are a few ways to fix an undefined variable: (1) You can rename the variable or variable set so that it matches what you have used in the topic; (2) you can re-insert the variable in the topic so that it uses an existing variable set/variable name, (3) you can add the undefined variable to the project as a new ...

How do I fix Undefined index name in PHP?

To resolve undefined index error, we make use of a function called isset() function in PHP. To ignore the undefined index error, we update the option error_reporting to ~E_NOTICE to disable the notice reporting.

What causes Undefined index in PHP?

Notice Undefined Index in PHP is an error which occurs when we try to access the value or variable which does not even exist in reality. Undefined Index is the usual error that comes up when we try to access the variable which does not persist.


2 Answers

mario's got it. Do this:

function phpRocks() {
    global $page;

    require("includes/dostuff.php");
}
like image 65
user428517 Avatar answered Oct 11 '22 18:10

user428517


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);
like image 36
deceze Avatar answered Oct 11 '22 18:10

deceze