PHP中的OOP问题与类

时间:2014-07-07 23:01:26

标签: php mysqli

我有两个类,一个是读取ini文件并创建mysqli对象的数据库类,另一个是通过数据库类加载的基本getter和setter。

我在这里错过了什么吗?

选项类:

<?php
class Options {

    var $table;
    var $table_definitions;
    var $opt_db;

function __construct()
{
$this->opt_db = new mysqli("localhost","db_usr","db_pass","db"); # works
$this->opt_db = new DBConfig("db.ini"); # doesn't work
$this->table = "options";
$this->table_definitions = "options_definitions";
}
?>

DBConfig类:

<?php
Class DBConfig extends mysqli {


    var $host; 
    var $database; 
    var $user; 
    var $pass;
    var $db; 


function __construct($fn)
{

$file = @parse_ini_file($fn);
        $this->host = $file[host]; 
$this->host = "p:".$this->host;
        $this->database = $file[dbname]; 
        $this->user = $file[uname]; 
        $this->pass = $file[pwd]; 

//$this->db = 
return $this->db =  new mysqli($this->host,$this->user,$this->pass,$this->database) or die(mysqli_error());

}
?>

为了让班级工作而不是做一行代码,需要做些什么。实际上,我不想为每个班级做这个吗?

由于

2 个答案:

答案 0 :(得分:1)

由于你要覆盖mysqli类的构造函数,你需要手动调用它,如下所示:

<?php
Class DBConfig extends mysqli {


    var $host; 
    var $database; 
    var $user; 
    var $pass;
    var $db; 


function __construct($fn)
{

  $file = @parse_ini_file($fn);
  $this->host = $file[host]; 
  $this->host = "p:".$this->host;
  $this->database = $file[dbname]; 
  $this->user = $file[uname]; 
  $this->pass = $file[pwd]; 

  return parent::__construct( $this->host , $this->user , $this->pass , $this->database );
}

答案 1 :(得分:0)

在这种情况下,您必须添加引号或撇号。

只需替换它:

    $this->host = $file[host]; 
    $this->host = "p:".$this->host;
    $this->database = $file[dbname]; 
    $this->user = $file[uname]; 
    $this->pass = $file[pwd];

用这个:

    $this->host = $file["host"]; 
    $this->host = "p:".$this->host;
    $this->database = $file["dbname"]; 
    $this->user = $file["uname"]; 
    $this->pass = $file["pwd"];

btw ... __construct()不返回值,而是返回类

的实例

改变这个:

return $this->db = $this->db =  new mysqli($this->host,$this->user,$this->pass,$this->database) or die(mysqli_error());

用这个:

parent::__construct( $this->host , $this->user , $this->pass , $this->database );