简体   繁体   中英

How to properly require PHP files

I'm using 2 main PHP files for scripts on my website. One that focuses on accessing data from a MySQL database and one that contains functions required for the website. In some functions (in the functions file) I need to call functions from my MySQL file. I don't understand how to properly require the files so they are usable when they are necessary.

include 'scripts/MySQL.php';
include 'scripts/functions.php';

Is at the top of the page's file (I use functions from both files directly). Then when I need to use MySQL functions in functions.php , the MySQL functions are null if I don't require MySQL.php at the top of the functions.php file, but if I do, I get this error: Fatal error: Cannot redeclare getUserInfo() (previously declared in .../scripts/MySQL.php:2) in .../scripts/MySQL.php on line 16 . This is getUserInfo(line 2 is the first line posted, and line 16 is the last):

function getUserInfo($steamID) {
    $link = mysqli_connect(constant('DB_SERVER'), constant('DB_USER'), constant('DB_PASS'), constant('DB_NAME'));

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    $query = 'SELECT * FROM '.constant('membersTable').' WHERE steamID = '.$steamID;

    if($result = mysqli_query($link, $query)) {
        return mysqli_fetch_assoc($result);
    }
}

How does require really work with inter-file dependencies? And why does my code act so weird/how do I fix it?

Also, if I want to access variables from another file, do I have to require that file in every function that uses the variables, or can I require it at the top of the file containing the functions (the latter does not seem to work)?

Sorry if this question reads a little confusing. I really could not figure out a good way to word my problem (especially cause I'm not sure I understand the problem myself).

use include_once or require_once to avoid redeclaring your functions

require_once 'scripts/MySQL.php';
require_once 'scripts/functions.php';

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again.

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