I'm trying to pass an object to another via constructor. I have a class that gathers up the database credentials and assigns them to the class properties. Then another class that does the actual query and returns an array of rows. Here's the code:
// GetCredentials
class GetCredentials
{
public function __construct()
{
}
private $_db = "";
private $_uname = "";
private $_pwd = "";
public function DB($value = NULL)
{
if( $value===NULL )
return $this->_db;
else
$this->_db = $value;
}
public function Uname($value = NULL)
{
if( $value===NULL )
return $this->_uname;
else
$this->_uname = $value;
}
public function Pwd($value = NULL)
{
if( $value===NULL )
return $this->_pwd;
else
$this->_pwd = $value;
}
public function readCreds($filename)
{
$parray = array();
$file = fopen($filename,"r");
while(! feof($file))
{
array_push($parray,fgets($file));
}
fclose($file);
$this->DB = $parray[0];
$this->Uname = $parray[1];
$this->Pwd = $parray[2];
}
}
// DBconnection
class DBconnection{
public function __construct(GetCredentials $cr)
{
$Uname = $cr->Uname;
$DB = $cr->DB;
$Pwd = $cr->Pwd;
}
private $conn;
private $Uname;
private $DB;
private $Pwd;
public function dbConnect($sql)
{
try {
$conn = new PDO("mysql:host=localhost;dbname=" . $DB, $Uname, $Pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$arr = $conn->prepare($sql);
$arr->execute();
$result = array();
$result = $arr->fetchAll();
return $result;
}
catch(PDOException $err) {
return "ERROR: Unable to connect: " . $err->getMessage();
}
}
function __destruct(){
$conn = null;
}
}
To test I've instantiated the GetCredentials class, populated the values, then passed to the DBConnection object values and all and have it do the actual data retrival. My test script looks like this:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
$sC = New GetCredentials();
$sC->readCreds('dbdata.txt');
$db = New DBConnection($sC);
$sql = 'SELECT `Member ID`, `Address 1`, City, State, Zip FROM `MemberDataAll` WHERE LENGTH(Zip) >= 5';
$rArr = $db->dbConnect($sql);
echo count($rArr);
My script throws a set of errors that state the properties of the DBConnection object are empty. I'm thinking it might be that my utilization is incorrect but I'm not sure. I'm also wondering if using $this in the constuctor is the best idea, is Self:: better and if so why? Can anyone set me straight? Thanks in advance.