我是 PHP OOP 的新手。下面是我的第一个类文件。我想为这段代码增加更多的灵活性,添加函数以便我可以运行查询,甚至将结果(fetch_assoc/fetch_array)分配给一个数组(或 var 等)以供以后使用。
我在运行查询时遇到的问题是我无法将两个类放在一起(嵌套?):$db->Query->Select('myTable');
OR $db->Query->Select('myTable')->Where($pageID);
OR$db->Query->Select('myTable')->Where($pageID)->OrderBy('name');
另外,如果您让我知道我在此代码中是否做错了什么以及改进建议,我将不胜感激,这样我将来可以编写更好的 php 类 =)。
<?php
require( $_SERVER['DOCUMENT_ROOT'] . '/database/database-connection-info.php');
//This file (database-connection-info.php) contains $config[];
class db {
private $db;
private $type = 'read-only';
//$config['db']['dbh'] = Database Host
//$config['db']['dbn'] = Database Name
//$config['db'][$type]['dbu'] = [User type][user name]
//$config['db'][$type]['dbp'] = [User type][password]
public function __construct($type = null) {
global $config;
$this->config = $config;
$this->Connect($type);
}
public function Connect($type) {
global $config;
switch( $type ) {
case 'admin':
$this->type = 'admin';
$this->db = mysql_connect( $this->config['db']['dbh'] , $this->config['db'][$type]['dbu'] , $this->config['db'][$type]['dbp'] );
return $this->db;
default:
$this->type = 'read-only';
$type = 'read';
$this->db = mysql_connect( $this->config['db']['dbh'] , $this->config['db'][$type]['dbu'] , $this->config['db'][$type]['dbp'] );
return $this->db;
}
}
public function Close() {
mysql_close();
mysql_close($this->db);
$this->type = 'Closed';
}
public function Type() {
return "<b>Database connection type</b>: " . $this->type . "<br/>";
}
public function Status() {
if( !@mysql_stat($this->db) )
{ return "<b>Database connection status</b>: There is no database connection open at this time.<br/>"; }
else { return "<b>Database connection status</b>: " . mysql_stat($this->db) . "<br/>"; }
}
}
//For testing purposes
$db = new db(admin);
echo $db->Type();
echo $db->Status();
echo $db->Close();
echo $db->Status();
echo $db->Type();
?>