简体   繁体   中英

Require/Include and Undefined Variables in PHP

SOLVED: The error had nothing to do with require or include. It was completely unrelated to the question. Sorry about that. :(

I thought I had an understanding of require/include until now. I have a file named file_one that has something like this, $user_data = return_user_data_as_array() . My second file file_two , calls $user_data . Now, when I do a include 'file_two.php' into the file_one page after the functions and variables have been called, the page returns with undefined variable user_data . I thought that if you include/require a file into your php code it would pick up any variables written in the original file? How would I fix this?

Edit: I also want to mention that although the undefined variable error is popping up on my screen, the "undefined" variables are correctly echoed out.

File One

//this require_once holds the function user_data()

require_once 'core/init.php';

$user_id = 1;

$profile_data = user_data($mysqli, $user_id); 

//this calls file two
require_once 'file_two.php';

File Two or file_two.php

echo $profile_data['full_name'];

The key thing here is to have your include before not after the function call. Also just include the function and then call it in file two.

I think you must have an error elsewhere on the page. If you're defining the variable outside of a function or class and you're including the file that uses it after it's been defined it should work fine:

file_one.php

<?php
function return_user_data_as_array(){
    return array('name'=>'BenD');
}

$user_data = return_user_data_as_array();

include('file_two.php');
?>

file_two.php

<?php
print_r( $user_data );
?>

Result:

Array
(
    [name] => BenD
)

This should all work fine. Your error is probably arising elsewhere (for instance, you might be calling $user_data from inside a function without specifying global $user_data , or you're calling $user_data somewhere in file_one.php accidentally?)

EDIT

Now that you've shown some code, I imagine that the problem is that user_data() isn't returning an array that includes the full_name key. Try print_r($profile_data) to see what the array looks like. I'm guessing that the problem lies in what's being returned from user_data() (if anything! make sure it includes a return $x clause in there! I've spent a lot of time trying to figure out a logical error when the only problem was that my function didn't return anything)

The answer had nothing to do with the problem in the question. The code in the question is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM