如何正确使用PHP要求 [英] How to properly use PHP require

查看:253
本文介绍了如何正确使用PHP要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个文件:index.phpdb.php(数据库)和functions.php

I have 3 files: index.php, db.php (database), and functions.php

下面是每个文件中的示例:

here is an example what is in each file:

database.php:

define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS", "1234");
define ("DB_NAME", "test");

try {
    $dsn = "mysql:dbname=".DB_NAME.";host=".DB_HOST;
    $dbh = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

index.php:

require $_SERVER['DOCUMENT_ROOT']."/config/db.php";
require $_SERVER['DOCUMENT_ROOT']."/config/functions.php";

if(isLoggedIn()) {
    echo "hi";
}

functions.php:

function isLoggedIn() {
    require $_SERVER['DOCUMENT_ROOT']."/config/db.php";

    $stmt = $dbh->prepare("SELECT * FROM users....");
    $stmt->execute();
}


我得到的错误是:


The error i get is:

注意:/var/www/config/database.php中已经定义了常量DB_HOST

Notice: Constant DB_HOST already defined in /var/www/config/database.php

我尝试过的事情:

我尝试在所有文件中将require替换为require_once,但是它给出的错误在这里:

I tried to replace require with require_once in all my files but the error that it gives is here:

致命错误:未捕获错误:在functions.php中调用成员函数prepare()上的空值

Fatal error: Uncaught Error: Call to a member function prepare() on null in functions.php

推荐答案

因此,由于这对您没有意义,所以我在这里的最后一个答案是您可以为彻底解决此问题而采取的措施的完整答案全部:

So, since it didn't make a sense to you my last answer here is a full answer of what you can do to get rid of this problem once for all:

db.php

<?php
$host="localhost"; 
$user="root"; 
$password="1234"; 
$db="test"; 

    try {
        $dbh = new PDO("mysql:host=$host;dbname=$db",$user,$password);
    } catch (PDOException $e) {
        die("DB ERROR: ". $e->getMessage());
    }
?>

index.php

require_once $_SERVER['DOCUMENT_ROOT']."/config/db.php";

if(isLoggedIn($dbh)) {
    echo "hi";
}

functions.php

function isLoggedIn($dbh) {
$stmt = $dbh->prepare("SELECT * FROM users....");
$stmt->execute(); 
}
function anotherfunction($dbh) {
$stmt = $dbh->prepare("SELECT * FROM others....");
$stmt->execute(); 
}

上述更正将为您省去处理需求的麻烦,您只需一次需要db.php,这样您现在就可以访问其变量并在需要时作为参数传递.

The above corrections will save you the pain of looking after the requires, you require the db.php once so that now you have access to its variable and pass as argument whenever needed.

注意:感谢Phil的卓有成效的评论和详尽的阐述.

Note: Thanks Phil for fruitful comments and good elaboration.

这篇关于如何正确使用PHP要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆