Why doesn't the object get passed into the 'class property'?
This f开发者_如何学JAVAeels like its obvious... I've created these two classes in php but I'm struggling to understand why the object doesn't seem to be passed back.
class DataAccess {
function dbconnect($query){
@ $db = new mysqli(MYHOST,MYDBUSER,DBUSERPASSWORD,MYDATABASE);
if (mysqli_connect_errno()) {
echo '<h1>there is an error with the database connection</h1>';
exit;
}
$result = $db->query($query);
$db->close();
return $result;
}
and...
class Run {
public $getdata;
public $jobdetails;
function __construct(){
$query = 'Select ID from jobs;';
$getdata = new DataAccess();
$jobdetails = $getdata->dbconnect($query);
}
function getJobList(){
print_r ($this->jobdetails);
}
}
and I call using this:
$mything = new Run();
now if I print_r($result);
from inside the dbconnect function it returns metadata, but if I do it once it's passed back to the Run class, it doesn't return anything.
What am I missing?
$jobdetails is local to __construct, if you want to have it local to the instance, use $this->jobdetails
Change this
$jobdetails = $getdata->dbconnect($query);
To this:
$this->jobdetails = $getdata->dbconnect($query);
Firstly, you shouldn't make a DB connection for each query you run. Connect in the constructor and then the connection will be closed automatically when the script ends
class DataAccess {
protected $_connection = null;
function __construct() {
$this->_connection = new mysqli(MYHOST,MYDBUSER,DBUSERPASSWORD,MYDATABASE);
if (mysqli_connect_errno()) {
echo '<h1>there is an error with the database connection</h1>';
exit;
}
}
function query($query){
return $this->_connection->query($query);
}
}
Secondly, you're not setting the instance variable properly.
Change:
$jobdetails = $getdata->dbconnect($query);
To:
$this->jobdetails = $getdata->dbconnect($query);
精彩评论