我正在创建一个使用公共(public)静态函数连接到数据库的站点。
因为它是由类名调用的,所以我不明白我将如何执行 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;
}
}
}
函数.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)
}
我该怎么办,还有别的办法吗?
最佳答案
我想你想做的是创建一个单例类,下面是一个例子
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";
希望对你有帮助
关于php - 在 mysqli 函数中使用公共(public)静态函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068156/