是否可以使 php 全局变量在函数作用域内自动可用?

发布于 2024-11-30 04:18:47 字数 292 浏览 2 评论 0原文

让我先解释一下。 我有一些全局数据库连接,并且有一些简单的函数,它们使用每个数据库连接并执行查询等。

因为我想多次使用这些连接,并且为了避免每次在每个函数中定义它们,我都将它们创建为文档顶部的全局变量。 然而我只是想知道,而不是必须写

global $mysql_db1, $mysql_db2, $mysql_db3, $mysql_db4, $mysql_db5;

是否有办法使这种情况发生,而不必每次都复制和粘贴它?

我知道这很微不足道,但我只是想加快自己的发展,

Let me start by explaining.
I have a few global database connections and have a few simple functions that use each one and perform queries and such.

Because i want to use the connections more then once, and to save me defining them each time in each function i have created them as globals at the top of the document.
However i am just wondering that instead of having to write

global $mysql_db1, $mysql_db2, $mysql_db3, $mysql_db4, $mysql_db5;

Is there anyway to make this happen without me having to copy and paste it each time?

I know its trivial but i just wanted to speed up my own development,

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

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

发布评论

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

评论(4

我不是你的备胎 2024-12-07 04:18:47

我将创建一个 ConnectionManager 类来存储这些连接,并使用该类的实例来执行使用 db 的任何函数:)

如果您不想每次都放置参数,那么使用 Singleton 也是一个好主意。

I'd create a class ConnectionManager which stores these connections and use an instance of the class for any function using the db :)

Using a Singleton is also a good idea if you don't want to put the parameter each time.

甚是思念 2024-12-07 04:18:47

最好的选择是以面向对象的方式声明它们,例如作为单例的属性,然后以这种方式访问​​它们。如果你坚持以一种会让后续开发人员伤心的方式做事,你可以使用 $GLOBALS 数组。全局变量只是一个主意,坦率地说,我希望该关键字可以从语言中删除。

您可以使用的一个非常简单的版本:

class ConnectionHolder
{
    public $mysql_db1;

    private static $inst;
    public static &getInstance()
    {
        if( !self::$inst )
            self::$inst = new ConnectionHolder();
        return self::$inst;
    }

    private function __construct()
    {
        $this->mysql_db1 = // ... you may want another nameing convension.
        // yada yada
    }
}

然后,在您的函数中:

$ch =& ConnectionHolder::getInstance()
$ch->mysql_db1;

Your best bet is to declare them in an object-oriented way, say as properties of a Singleton, and then access them that way. If you are insistent on doing things in a way which will make subsequent developers sad, you can use the $GLOBALS array. Globals are just a bad idea, and I wish that the keyword could be struck from the language, frankly.

A very simple version of something you could use:

class ConnectionHolder
{
    public $mysql_db1;

    private static $inst;
    public static &getInstance()
    {
        if( !self::$inst )
            self::$inst = new ConnectionHolder();
        return self::$inst;
    }

    private function __construct()
    {
        $this->mysql_db1 = // ... you may want another nameing convension.
        // yada yada
    }
}

Then, in your functions:

$ch =& ConnectionHolder::getInstance()
$ch->mysql_db1;
一袭白衣梦中忆 2024-12-07 04:18:47

全局变量通常被认为是不好的做法。我不会对你武断地谈论它,但请查看这篇文章:http://blog.case.edu/gps10/2006/07/22/why_global_variables_in_php_is_bad_programming_practice

您可以使用 $GLOBALS 超全局变量来访问已定义的任何变量。在全局范围内定义(文档)。因此,在您的示例代码中,只需使用 $GLOBALS['mysql_db1'] 就相当于使用 global $mysql_db1; 行,然后使用 $mysql_db1

我无法充分强调(不武断地)这是一个多么糟糕的计划。在整个开发过程中,您可能对此没什么问题,但是可怜的 Johnny Nextguy,如果您包含也使用全局变量的第三方脚本,那么代码之神可能会拯救您......并且存在变量冲突名称。现在你就上当了!

正如所建议的,您最好将数据库功能封装在一个类中。如果您使用静态类,您仍然拥有全局变量的所有优点,而没有污染范围或覆盖的危险。

这是一个示例数据库类及其用法:

// put this in a library file or some place that all scripts include
require_once('database_class.php');
$db = new db(array(
 'host'=>'localhost'
 'user'=>'db_user_name'
 'password'=>'db_password',
 'database_name'=>'my_database'
));


// now anywhere in code you want to use it
$array = db::getRows('SELECT id, name FROM users');
$field = db::getField('SELECT name FROM users WHERE id=10');


<?php
// database_class.php
class db {
    static protected $resource_link = null;

    function __construct($args=false) {
        if ($args===false || !is_array($args))
            return false;
        if (
            !isset($args['host']) ||
            !isset($args['user']) ||
            !isset($args['password']) || 
            !isset($args['database_name'])
        )
            return critical_error('Missing database configuration data.');


        self::$resource_link = @mysql_connect($args['host'],$args['user'],$args['password']);
        if (!self::$resource_link)
             return critical_error('Error connecting to database 2001.  MySQL said:<br>'.mysql_error());
        @mysql_select_db($args['database_name'],  self::$resource_link);
        return;
    }


    // return a single-dimmension array of fields as string
    static public function getFields ($sql=false, $field=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $res = array();
                 while ($this_row = mysql_fetch_array($query_obj)) {
                    if ($field !== false && isset($this_row[$field]))
                        $res[] = $this_row[$field];
                    else
                        $res[] = $this_row[0];
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single-dimmension array of fields as string with keyfield as key
    static public function getKeyFields ($sql=false, $key_field='id', $list_field='id') {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                 while ($this_row = mysql_fetch_array($query_obj)) {
                    if (isset($this_row[$key_field]))
                        $res[$this_row[$key_field]] = $this_row[$list_field];
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single field as string from the first row of results
    static public function getField ($sql=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $this_array = mysql_fetch_array($query_obj);
                if (is_array($this_array))
                    return $this_array[0];
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single row as an array
    static public function getRow ($sql=false) {  
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj)
                $res = mysql_fetch_assoc($query_obj);
        } // end :: if $sql is not false
        return $res;
    }

    // return an array of rows as arrays of strings
    static public function getRows ($sql=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            $res = array();
            if ($query_obj) {
                 while ($this_row = mysql_fetch_assoc($query_obj)) {
                    $res[] = $this_row;
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return an array of rows as arrays of strings, using specified field as main array keys
    static public function getKeyRows ($sql=false, $key_field='id', $include_key_in_results=true) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $res = array();
                 while ($this_row = mysql_fetch_assoc($query_obj)) {
                    if (isset($this_row[$key_field])) {
                        $res[$this_row[$key_field]] = $this_row;
                        if ($include_key_in_results == false)
                            unset($res[$this_row[$key_field]][$key_field]);
                    } // end :: if checking for key field in result array
                } // end :: while looping query obj
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }


    // do an update query, return true if no error occurs
    static public function update ($sql=false) {
        $res = false;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj && strlen(mysql_error()) < 1)
                $res = true;
        }
        return $res;
    }

    // do an insert query, return the auto increment ID (if there is one)
    static public function insert ($sql=false) {
        $res = null;
        if ($sql !== false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj)
                $res = mysql_insert_id(self::$resource_link);
        }
        return $res;
    }    
}
?>

Globals are usually regarded as bad practice. I won't pontificate at you about it, but check out this article: http://blog.case.edu/gps10/2006/07/22/why_global_variables_in_php_is_bad_programming_practice

You can use the $GLOBALS superglobal to access any variable that has been defined in the global scope (docs). Thus, in your example code, simply using $GLOBALS['mysql_db1'] would be the equivalent of having the line global $mysql_db1; and then using $mysql_db1.

I cannot stress enough (without pontificating) how bad of a plan this is. YOU might be all right with it the entire time you're developing, but poor poor Johnny Nextguy, and may the Gods of Code save you if you include a third-party script that also uses globals... and there's a conflict of variable names. Now you're in for it!

As has been suggested, you are better off encapsulating your database functionality in a class. If you use a static class, you still have all the benefits of a global variable without a polluted scope or danger of overwriting.

Here is a sample database class, along with usage:

// put this in a library file or some place that all scripts include
require_once('database_class.php');
$db = new db(array(
 'host'=>'localhost'
 'user'=>'db_user_name'
 'password'=>'db_password',
 'database_name'=>'my_database'
));


// now anywhere in code you want to use it
$array = db::getRows('SELECT id, name FROM users');
$field = db::getField('SELECT name FROM users WHERE id=10');


<?php
// database_class.php
class db {
    static protected $resource_link = null;

    function __construct($args=false) {
        if ($args===false || !is_array($args))
            return false;
        if (
            !isset($args['host']) ||
            !isset($args['user']) ||
            !isset($args['password']) || 
            !isset($args['database_name'])
        )
            return critical_error('Missing database configuration data.');


        self::$resource_link = @mysql_connect($args['host'],$args['user'],$args['password']);
        if (!self::$resource_link)
             return critical_error('Error connecting to database 2001.  MySQL said:<br>'.mysql_error());
        @mysql_select_db($args['database_name'],  self::$resource_link);
        return;
    }


    // return a single-dimmension array of fields as string
    static public function getFields ($sql=false, $field=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $res = array();
                 while ($this_row = mysql_fetch_array($query_obj)) {
                    if ($field !== false && isset($this_row[$field]))
                        $res[] = $this_row[$field];
                    else
                        $res[] = $this_row[0];
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single-dimmension array of fields as string with keyfield as key
    static public function getKeyFields ($sql=false, $key_field='id', $list_field='id') {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                 while ($this_row = mysql_fetch_array($query_obj)) {
                    if (isset($this_row[$key_field]))
                        $res[$this_row[$key_field]] = $this_row[$list_field];
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single field as string from the first row of results
    static public function getField ($sql=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $this_array = mysql_fetch_array($query_obj);
                if (is_array($this_array))
                    return $this_array[0];
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return a single row as an array
    static public function getRow ($sql=false) {  
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj)
                $res = mysql_fetch_assoc($query_obj);
        } // end :: if $sql is not false
        return $res;
    }

    // return an array of rows as arrays of strings
    static public function getRows ($sql=false) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            $res = array();
            if ($query_obj) {
                 while ($this_row = mysql_fetch_assoc($query_obj)) {
                    $res[] = $this_row;
                }
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }

    // return an array of rows as arrays of strings, using specified field as main array keys
    static public function getKeyRows ($sql=false, $key_field='id', $include_key_in_results=true) {
        $res = null;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj) {
                $res = array();
                 while ($this_row = mysql_fetch_assoc($query_obj)) {
                    if (isset($this_row[$key_field])) {
                        $res[$this_row[$key_field]] = $this_row;
                        if ($include_key_in_results == false)
                            unset($res[$this_row[$key_field]][$key_field]);
                    } // end :: if checking for key field in result array
                } // end :: while looping query obj
            } // end :: if query object is not null
        } // end :: if $sql is not false
        return $res;
    }


    // do an update query, return true if no error occurs
    static public function update ($sql=false) {
        $res = false;
        if ($sql!==false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj && strlen(mysql_error()) < 1)
                $res = true;
        }
        return $res;
    }

    // do an insert query, return the auto increment ID (if there is one)
    static public function insert ($sql=false) {
        $res = null;
        if ($sql !== false) {
            $query_obj = mysql_query($sql, self::$resource_link);
            if ($query_obj)
                $res = mysql_insert_id(self::$resource_link);
        }
        return $res;
    }    
}
?>
ぺ禁宫浮华殁 2024-12-07 04:18:47

直接回答你的问题:不。

对您问题的实际回答表明,全局变量并不是一个热门想法。请注意,我认为大多数争论都是无效的,并且围绕着其他人说“呃,这太恶心了!”或“你会释放魔鬼!”。

然而,他们都围绕着这个问题:如果程序的两个部分尝试使用相同的全局变量 $foo 来实现不同的目的(即,不小心他们决定使用相同的名称),那么就会有不保证会发生错误。这就是为什么建议使用不同的存储方式,比如一个类,因为两个名为Foo的类肯定会导致错误。

在您的程序上下文中,人们可能会建议创建一个 ConnectionManager 单例,您可以通过编写类似 $conn1 = ConnectionManager::getConnection('conn1');$conn1 = ConnectionManager::getConnection('conn1'); 的内容来获取数据库连接。代码>.

In direct answer to your question: no.

A practical answer to your question points out that globals are not such a hot idea. Be aware that most of the arguments out there I believe are invalid and revolve around others saying "ewww, that's gross!" or "you'll unleash the devil!".

However, they all sort of dance around this one issue: if two parts of your program try to use the same global variable $foo for different purposes (ie, accidentally they decided on the same name) then there is no guarantee an error will occur. This is why it is recommended to use a different storage method, such as a class, because two classes named Foo will definitely cause an error.

In context of your program, one would probably recommend creating a ConnectionManager singleton, where you could grab database connections by writing something like $conn1 = ConnectionManager::getConnection('conn1');.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文