PHP通过构造函数传递对象作为参数

问题描述 投票:0回答:1

我正在尝试通过构造函数将一个对象传递给另一个对象。我有一个收集数据库凭据并将其分配给类属性的类。然后是另一个进行实际查询并返回行数组的类。这是代码:

    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;
    }           
}

为了测试,我实例化了GetCredentials类,填充了值,然后传递给DBConnection对象值以及所有值,并让它进行实际的数据检索。我的测试脚本如下所示:

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.

code \ oops忘记了凭证类类GetCredentials{公共功能__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];
    }   

} `code`
php class database-connection
1个回答
0
投票

首先,我将更改类readCreds中的方法GetCredentials并确保它在该类的私有变量中分配了凭据:

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]);
} 

在我愿意之后:

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

然后在DBconnection类中,我将更改构造函数以将那些凭据正确分配给私有变量。而且我会在使用这些变量实例化$this时添加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;
    }           
}

测试是否可以解决您的问题。

© www.soinside.com 2019 - 2024. All rights reserved.