1

我做了一个这样的数据库连接类:

class db_connector{

const host = "localhost"; 
const user = "root"; 
const password = ""; 
const dbname = "test"; 

public $db;

public function __construct()
{
    $database = $this::dbname;
    $db = new mysqli($this::host, $this::user, $this::password, $this::dbname);
    if($db->connect_errno)
    {
        die (mysql_connect_error());
    }
    return $db;
}
}

当我为类创建一个对象时,它工作得很好,但是我想在类中进行查询,但出现以下错误:

致命错误:调用未定义的方法 db_connector::query()

对象如下(类外):

$con = new db_connector;
$con->query("SELECT * FROM test");

连接建立,只是查询给出了错误。我认为该对象将继承 mysqli 方法,因为我返回了它。任何人都可以帮我解决这个问题吗?我在 OOP 中相当新,所以也许我的逻辑不是最好的。

4

2 回答 2

0

来个小魔法怎么样:

class db_connector{

protected $connectionData = array(
    'host' => 'localhost',
    'user' => 'root',
    'password' => '',
    'dbname' => 'test',
);

protected $db;

public function __construct($connectionData=array())
{
    $cd = array_merge($this->connectionData, $connectionData);
    $this->db = new mysqli($cd['host'], $cd['user'], $cd['password'], $cd['dbname']);

    if($this->db->connect_errno)
    {
        die (mysql_connect_error());
    }
}

public function foo()
{
    return 'I am foo, i exist so i will be called even if mysqli::foo would exist, because i am defined in this class!';
}

public function __get($property)
{
    if(property_exists($this->db, $property)){
        return $this->db->$property;
    }  
}

public function __call($name, $args)
{
    if(method_exists($this->db, $name))
        return call_user_func_array(array($this->db, $name), $args);
}
}

并称它为:

$db = new db_connector();
$result = $db->query('SELECT foo FROM bar LIMIT 1');
// this should also work:
echo $result->num_rows;
于 2013-04-13T11:26:13.907 回答
0

类构造函数不会像您期望的那样返回 mysqli 对象。

$con = new db_connector;
//$con is a db_connector object not a mysqli object
$con->query("SELECT * FROM test");

尝试:

$con = new db_connector;
$con->db->query("SELECT * FROM test");

反而。$con->db 是一个保存 mysqli 对象的公共字段。

编辑

也改变:

$db = new mysqli($this::host, $this::user, $this::password, $this::dbname);
if($db->connect_errno)
{
    die (mysql_connect_error());
}
return $db;

至:

$this->db = new mysqli($this::host, $this::user, $this::password, $this::dbname);
if($this->db->connect_errno)
{
    die (mysql_connect_error());
}
于 2013-04-13T11:14:09.787 回答