类外的Mysqli查询错误

时间:2013-04-13 11:07:54

标签: php mysqli

我创建了一个像这样的数据库连接类:

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中相当新,所以也许我的逻辑并不是最好的。

2 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分: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;