Accessing a mySQLi database object from a method
I am trying to create a class with various methods that will need to interact with a database, so I am trying to create a database object using mySQLi in the __construct, depending on if I still have a db connection or not, but I am unsure of how I can access the db object from within a method as I am new to object oriented PHP, here is my code,
class my_class
{
private $db_host = '';
private $db_user = '';
private $db_pass = '';
private $db_name = '';
function __construct() {
$myconn = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if($myconn) {
$this->con = true;
return true;
} else {
return false;
}
}
开发者_开发知识库
private function my_function(){
//not sure how I can access the database object from here to run a query
}
}
any advice on how I can improve this, or approach this in a better way, will be appreciated!
Please excuse my ignorance on the subject!
Thanx in advance guys!
Store the object ($myconn) in an member of the object.
$this->oConnection = $myconn;
Then you can simply use $this->oConnection
to access your object.
Mind the deceleration in of your new member private $oConnection
at the top of your class.
精彩评论