我在PHP中创建了一个用户数据库抽象类,它扩展了我所做的一个名为DBO(数据库对象)的基类。 DBO对象的工作就是将$db
作为我的codeigniter的$db
引用。
理想情况下,在我的User对象中,我可以$this->db->insert()
并访问我的codeigniter的数据库对象。
这是我的代码:
DBO:
class DBO {
public $db;
public $ci;
//put your code here
public function __construct() {
$ci =& get_instance();
$this->db =& $ci->db;
}
}
USER :(扩展了DBO)
class User extends DBO{
/** User id of the user
* @var int */
public $user_id;
/** User's first name in english
* @var string */
public $first_name;
/** User's last name in english
* @var string */
public $last_name;
/** User's name in Korean
* @var string */
public $korean_name;
/** User's phone number
* @var string */
public $phone;
/** User's email address
* @var string */
public $email;
/**
* Creates a new user from a row or blank.
* Creates a new user from a database row if given or an empty User object if null
*
* @param Object $row A row object from table: admin_users
*/
public function __construct(stdClass $row = null){
if($row){
if(isset($row->user_id)) $this->user_id = $row->user_id;
if(isset($row->first_name)) $this->first_name = $row->first_name;
if(isset($row->last_name)) $this->last_name = $row->last_name;
if(isset($row->korean_name)) $this->korean_name = $row->korean_name;
if(isset($row->phone)) $this->phone = $row->phone;
if(isset($row->email)) $this->email = $row->email;
}
}
/**
* Saves this user to the database.
* @return boolean Whether this was successfully saved to the database.
*/
public function create(){
$data = array(
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'korean_name' => $this->korean_name,
'phone' => $this->phone,
'email' => $this->email,
);
if($this->db->insert(Tables::$USERS, $data) && $this->db->affected_rows() == 1){
$this->user_id = $this->db->insert_id();
return true;
} else {
return false;
}
}
但每当我尝试使用$this->db->insert()
时,就会显示Call to a member function insert() on a non-object.
有没有办法让这项工作?还是从根本上说错了?我的User类是否只保存信息,并将User对象传递给我的Users模型对象并运行数据库功能?
感谢您的帮助
答案 0 :(得分:2)
您缺少对父构造函数的调用。使用
parent::__contstruct()
在您的用户类构造函数中。通过这样做,将调用父类构造函数,因此将初始化db对象,您将能够使用它。
您还应该阅读此内容
http://www.techflirt.com/tutorials/oop-in-php/inheritance-in-php.html
了解继承。请阅读有关OOP的内容,以便了解PHP提供的OOP功能。