所以我有一个我在web应用中使用的函数列表。然而,大多数函数调用数据库类。这里有两个功能,例如:为多个函数声明一个全局对象
function add_post($userid,$body,$cat_id,$user_link){ //This function inserts new posts into the db
$db = new MysqliDb('localhost', 'root', 'root', 'my_db');
$now = date("Y-m-d H:i:s");
$insertData = array(
'user_id' => $userid,
'body' => $body,
'stamp' => $now,
'cat_id' => $cat_id,
'link' => $user_link
);
$db->insert('posts', $insertData);
}
function grab_username($userid){ //This function takes a user id, and returns the associated user_name
$db = new MysqliDb('localhost', 'root', 'root', 'my_db');
$params = array($userid);
$results = $db->rawQuery("SELECT username FROM users WHERE id = ?", $params);
//print_r($results);
foreach($results as $arrays){
foreach($arrays as $name){
return $name;
}
}
}
的问题是,我经常写行:
$db = new MysqliDb('localhost', 'root', 'root', 'my_db');
有没有一种方法,我可以在全球声明变量,有更多的东西是这样的:
$db = new MysqliDb('localhost', 'root', 'root', 'my_db');
function add_post($userid,$body,$cat_id,$user_link){ //This function inserts new posts into the db
$now = date("Y-m-d H:i:s");
$insertData = array(
'user_id' => $userid,
'body' => $body,
'stamp' => $now,
'cat_id' => $cat_id,
'link' => $user_link
);
global $db->insert('posts', $insertData);
}
我希望你是不严肃的。为每个类创建一个单独的数据库连接? –
如果他只使用这个类的单个实例,就像我个人解释他的问题一样,这样可以。如果他使用多个实例,那么明显的依赖注入或获取单个数据库实例的一些中心方法会更好。 – helion3
这不是他的应用程序中唯一的类。 –