i have created database class in php but i can't understand wh开发者_开发知识库y it has an error:
Fatal error: Using $this when not in object context in C:\xampp\htdocs\test1\Engine\Class\user.php on line 9
here is a code
<?php
class user{
private $db_host = 'localhost';
private $db_user = 'root';
private $db_password = '123456';
private $db_name = 'test';
private function _dbconnect(){
mysql_connect($this->db_host, $this->db_user, $this->db_password) or die('Unable to connect to Database'); // line 9 (error is here)
@mysql_select_db($this->db_name) or die( "Unable to select database");
}
public function login(){
self::_dbconnect();
mysql_close();
}
}
?>
In your function login you have to do
$this->_dbconnect()
in stead of
self::_dbconnect()
Bye doing it that way, you are calling the method statically, and thus, using $this
in the _dbconnect
method does not work.
You are calling the method statically
self::_dbconnect();
A static context has no object and therefore $this
is undefined.
$this->dbconnect();
first _dbconnect is not a static function and you are calling it as a static function
change self::_dbconnect(); to $this->_dbconnect();
you are all wrong here is a sollution:
$user = new user();
<?php
class user{
private $db_host = 'localhost';
private $db_user = 'root';
private $db_password = '123456';
private $db_name = 'test';
private function _dbconnect(){
//***********************************************
$user = new user();
//***********************************************
mysql_connect($this->db_host, $this->db_user, $this->db_password) or die('Unable to connect to Database'); // line 9 (error is here)
@mysql_select_db($this->db_name) or die( "Unable to select database");
}
public function login(){
self::_dbconnect();
mysql_close();
}
}
?>
now everything works fine
精彩评论