PHP 在函数之外需要文件

发布于 2025-01-01 09:56:33 字数 817 浏览 2 评论 0原文

有没有办法在函数之外包含文件并使其工作?

IE。我有一个文件 db.inc.php,其中包含我的数据库连接字符串:

switch (DB_TYPE) {
case MYSQL :
    try {
        $DBH = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "", DB_USER, DB_PASS);
        $DBH -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Error in Connection" . $e -> getMessage();
    }
}

现在我在我的函数文件,functions.php 中需要此文件:

require('db.inc.php')
function add() {

        $n = $DBH -> prepare("");
        $n -> execute((array)$s);
}

因此该文件已正确添加,但我的函数无法访问 $DBH 句柄。只有当我将该文件包含在我的函数中时:

function add(){
require('db.inc.php')

....etc....

}

我的函数才会起作用。

由于我将在许多文件中至少有 4-5 个函数,是否有可能只在函数之外要求它并使函数正常工作?

感谢和问候

Is there a way to include a file outside of a function and have it work?

ie. I have a file db.inc.php, this contains my db connection string:

switch (DB_TYPE) {
case MYSQL :
    try {
        $DBH = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . "", DB_USER, DB_PASS);
        $DBH -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch(PDOException $e) {
        echo "Error in Connection" . $e -> getMessage();
    }
}

Now I have require this file my in my functions file, functions.php:

require('db.inc.php')
function add() {

        $n = $DBH -> prepare("");
        $n -> execute((array)$s);
}

so the file is added in properly, but my function cannot access the $DBH handle. Only when I include the file in my function:

function add(){
require('db.inc.php')

....etc....

}

will my function work.

As I am going to have at least 4-5 functions in many files, any possibility of just requiring it outside the function and get the function to work?

Thank and regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

老旧海报 2025-01-08 09:56:33

在函数外部包含文件后,您可以将变量声明为全局变量,但这确实是一个糟糕的方法。相反,您应该让函数的调用者传递句柄作为参数。如果做不到这一点,您可以为数据库创建一个工厂并在每个函数中调用它。

为什么必须在函数外部调用require

After including the file outside the function, you could declare the variable as global, but that's really a bad way to do things. Instead, you should have the caller of the function pass handle as an argument. Failing that, you could create a factory for the database and call it within each function.

Why do you have to call the require outside the function?

我还不会笑 2025-01-08 09:56:33

实际上,全局变量的唯一替代方法是使用面向对象的技巧和技术。例如,如果您将功能实现为一组类,那么您始终可以访问任何静态公共类变量,因为它们是全局的。另一种方法是对单个对象类使用标准 PHP 模式。这与您的情况尤其相关,因为您似乎正在包装标准 PDO 类。就我而言,我使用 mysqli,但应用了相同的技术。任何模块都可以使用AppDB::get()访问数据库对象。以下是我的模块的序言,旨在为您提供这个想法(我已经修剪了 doxygen 文档以使其简短):

class AppDB extends mysqli {            

    /**            
     * This class uses a standard single class object pattern.            
     */            
    private static $_instance;            
    private static $_class = __CLASS__;            
    private function __clone() {}            
    /**            
     * Initialise the blog context. This is a static method since only one AppDB instance is allowed. The            
     * $connectParams must be provided on first invocation.            
     */            
    public static function get() {            

        if ( !isset( self::$_instance) ) self::$_instance = new self::$_class ();            
        return self::$_instance;            
    }            

    /**            
     * AppDB constructor. Connect to the database and initialise the list of tables with the given prefix.            
     */            
    private function __construct() {            

        parent::init();            
        list( $host, $db, $user, $passwd, $this->tablePrefix ) = explode ( ':', SQL_CONTEXT );            

        if( !parent::real_connect($host, $user, $passwd, $db)) {            
            throw new Exception ('Connect Error (' .             
                mysqli_connect_errno() . ') ' . mysqli_connect_error() );            
        }            
        ...            
    }
    ...
}

Really the only alternative to globals is to use object orientated tricks and techniques. For example if you implement your functionality as a set of classes then you can always access any static public class variables, as they will be global. Another way is to use a standard PHP pattern for a single object class. This is especially relevant in your case as you seem to be wrapping the standard PDO class. In my case, I use mysqli, but the same technique applies. Any module can access the database object using AppDB::get(). Here is the preamble to my module to give you the idea (I've trimmed the doxygen documentation to keep it short):

class AppDB extends mysqli {            

    /**            
     * This class uses a standard single class object pattern.            
     */            
    private static $_instance;            
    private static $_class = __CLASS__;            
    private function __clone() {}            
    /**            
     * Initialise the blog context. This is a static method since only one AppDB instance is allowed. The            
     * $connectParams must be provided on first invocation.            
     */            
    public static function get() {            

        if ( !isset( self::$_instance) ) self::$_instance = new self::$_class ();            
        return self::$_instance;            
    }            

    /**            
     * AppDB constructor. Connect to the database and initialise the list of tables with the given prefix.            
     */            
    private function __construct() {            

        parent::init();            
        list( $host, $db, $user, $passwd, $this->tablePrefix ) = explode ( ':', SQL_CONTEXT );            

        if( !parent::real_connect($host, $user, $passwd, $db)) {            
            throw new Exception ('Connect Error (' .             
                mysqli_connect_errno() . ') ' . mysqli_connect_error() );            
        }            
        ...            
    }
    ...
}
陌若浮生 2025-01-08 09:56:33

您可以使用 global 运算符:

require('db.inc.php')
function add() {
        global $DBH;
        $n = $DBH -> prepare("");
        $n -> execute((array)$s);
}

You can use the global operator:

require('db.inc.php')
function add() {
        global $DBH;
        $n = $DBH -> prepare("");
        $n -> execute((array)$s);
}
脱离于你 2025-01-08 09:56:33

您只想使用 global 关键字将其带入函数的范围:

function add() {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}

请参阅 此链接 有关变量范围的更多阅读。

您也可以使用 $GLOBALS,但我不喜欢这种方法。

或者,您可以在调用 add() 时通过引用传递句柄:

add($DBH);

function add(&$DBH) {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}

You just want to use the global keyword to bring it in the function's scope:

function add() {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}

See this link for more reading on variable scope.

You could also use $GLOBALS, but I'm not a fan of this approach.

Alternatively, you could pass the handle by reference when you call add():

add($DBH);

function add(&$DBH) {
    global $DBH;
    $n = $DBH -> prepare("");
    $n -> execute((array)$s);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文