简体   繁体   中英

PHP Pass an Object as a Parameter via the Constructor

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.

First, I would change the method readCreds in the class GetCredentials and make sure it assigns the credentials in the private variables of the class:

public function readCreds($filename)
{
    $parray = [];
    $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]);
} 

After I would test it as such:

$sC = New GetCredentials();
$sC->readCreds('dbdata.txt');
echo $sC->DB();    
echo $sC->Uname();
echo $sC->Pwd();

Then in the DBconnection class, I would change the constructor to properly assign those credentials to the private variables. And I would add $this keyword when using those variables to instantiate the PDO object :

// DBconnection
class DBconnection{

    private $conn;
    private $Uname;
    private $DB;
    private $Pwd;

    public function __construct(GetCredentials $cr)
    {   
        $this->Uname = $cr->Uname();
        $this->DB = $cr->DB();
        $this->Pwd = $cr->Pwd();
    }

    public function dbConnect($sql)
    {
        try {
            $this->conn = new PDO("mysql:host=localhost;dbname=" . $this->DB, $this->Uname, $this->Pwd);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $arr = $this->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;
    }           
}

Test if this solves your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM