在mysqli函数中使用公共静态函数

时间:2015-06-26 08:10:28

标签: php mysqli static static-methods

我正在创建一个使用公共静态函数连接到数据库的站点。 由于类名调用,我无法理解如何执行mysqli_query()。以下是代码:

db.class.php

<?php
class connect
{
    private static $db_host='localhost';

    private static $db_user='root';

    private static $db_pass='';

    private static $db_name='i_constuddoer01';

    //using public static function to avoid overloading
    public static function cxn_mysqli() {
        $result=mysqli_connect(self::$db_host,self::$db_user,self::$db_pass,self::$db_name);
        if(!$result)
            header("Location: sorry.php");
        else 
            return $result;
        }
    }
}

的functions.php

<?php
require_once('db.class.php');

function addUser($fname,$lname,$email,$pass) {
    $query="INSERT INTO users VALUES(...)";
    $qr_status = mysqli_query(connect::cxn_mysqli(),$query)
}

我该怎么办,还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

我认为你要做的是创建一个单例类,下面是一个

的例子
class Connect
{
    private static $instance;

    # make the construct private to avoid anyone using new Connect()
    private function __construct()
    {
        # Sql connect code in here
    }

    static public function i()
    {
        if(!is_object(self::$instance)) {
            return new self;
        }
        return self::$instance;
    }
}

# Lets try to create two instances
$i = Connect::i();
$j = Connect::i();

# Oh look they are exactly the same object
echo spl_object_hash($i)."\n";
echo spl_object_hash($j)."\n";

希望有所帮助