【问题标题】:Using public static function in mysqli functions在 mysqli 函数中使用公共静态函数
【发布时间】:2015-09-13 02:40:03
【问题描述】:

我正在创建一个使用公共静态函数连接到数据库的站点。 因为它是由类名调用的,所以我不明白我将如何执行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)
}

我该怎么办,有没有其他办法?

【问题讨论】:

  • 您只想使用现有的连接类吗?或者你正在写这门课,你想要反馈吗?

标签: php mysqli static static-methods


【解决方案1】:

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

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";

希望有帮助

【讨论】:

  • 既然mysqli默认是长连接的,为什么要为mysqli使用单例呢?
猜你喜欢
  • 1970-01-01
  • 2014-12-28
  • 2019-10-02
  • 2013-05-01
  • 2013-05-13
  • 2016-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多