PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
//DB.class.php
class DbMysql{
var $hostName;
var $userName;
var $password;
var $dbName;
var $dbh;//database connection handle
//constructor and connecting to the database not shown
function executeQuery($query){
if (!is_resource($this->dbh)){
$this->connectDB();//connect to the db if not connected
}
$stmt = new DbMysqlStatement($this->dbh, $query);
return $stmt;//return an object of DbMysqlStatement
}
}
class DbMysqlStatement{
var $query;
var $result;
var $dbh;
function DbMysqlStatement($dbh, $query, $result = ""){
echo "dbmysqlstatement constructor called!!!";
$this->dbh = $dbh;
$this->query = $query;
if (!is_resource($this->result)){
$this->computeResult();//compute result if not computed before
}
}
function computeResult(){
echo "computeresult called!!!";
if (is_resource($this->dbh)){
$this->result = mysql_query($this->query, $this->dbh);
}
}
function fetchRow(){
echo "dbmysqlstatement fetchrow called!!!";
if (is_resource($this->result)){
return mysql_fetch_row($this->result);//return a row
}
}
function fetchAssoc(){
if (is_resource($this->result)){
return mysql_fetch_row($this->result);//return an associative array
}
}
}
?>
<?php
//dbAccess.php
include("DB.class.php");
$dbInstance = new DbMysql();
$dbInstance->connectDb();
$query = "select * from Members_tbl";
$tempArray = array();
$tempArray = $dbInstance->executeQuery($query)->fetchRow();//this doesnot run
//but this runs perfectly and displays all the details in the Members_tbl
//$stmt = $dbInstance->executeQuery($query);
//$tempArray = $stmt->fetchRow();
$iterations = count($tempArray);
//echo $iterations;
for ($i = 0; $i < $iterations; $i++){
echo "<br />".$tempArray[$i];
}
?>
You could that in the second file I have commented a line
$dbInstance->executeQuery($query)->fetchRow();
The first part on execution[$dbInstance->executeQuery($query)] returns an object of the second class.
so I thought [$secondClassObject->fetchRow()] should work.
<?php
class foo
{
function sayHi()
{
echo "Hi";
}
}
class bar
{
function &fooMe()
{
$this->foo =& new foo();
return $this->foo;
}
}
$barMe =& new bar();
$barMe->fooMe()->sayHi();
?>
However, you should be very careful when doing this kind of code. If the first method returns something other than the object expected, you're in a world of hurt. It's better to play it safe and store off the return from the first method to make sure it's an object of type you wanted.