如何调用DbConnect类并将其用于另一个类,如FormElement类?
main.class.php
class DBCONNECT
{
public $dbConnection;
public function __construct($dbHost, $dbUsername, $dbPassword, $dbName){
$this->dbConnection = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($this->dbConnection->error){
trigger_error("Sorry couldn't connect to database :("); // problem connect to database
}else{
return true; // connection successfully
}
}
}
我的另一个班是
element.class.php
class FormElement
{
public function getCmbPovinsi(){
$userSqlQuery = "SELECT id,provinsi FROM aud_provinsi ORDER BY provinsi";
$userSys = $this->dbConnection->query($userSqlQuery) or die($this->dbConnection->error);
if ($userSys) {
/* checking for available users */
if($userSys->num_rows > 0){
echo'<div class="col_one_fourth">
<label for="provinsi">Provinsi<small>*</small></label>
<select id="provinsi" name="provinsi" class="sm-form-control required">
<option value="">-- Pilih Provinsi --</option>';
while ($userResult = $userSys->fetch_assoc()) {
echo '<option value="'.$userResult['id'].'">'.$userResult['provinsi'].'</option>';
}
echo '</select>
</div>';
}else{
echo "Error Handling!!";
}
}else{
echo "invalid query : ".$this->dbConnection->error."<br>";
echo "whole query : ".$userQuery ."<br>";
}
}
}
以及此代码如何正常工作?
答案 0 :(得分:1)
在element.class.php中首先需要main.class.php PATH。
require 'main.class.php';
class FormElement
{
protected $connection;
public function __construct(DBCONNECT $connection)
{
$this->connection = $connection;
}
public function getCmbPovinsi()
{
...
$this->connection->query(...);
}
}
此方法称为依赖注入。现在,当你想使用元素时,你可以创建一个这样的对象:
$element = new FormElement(new DBCONNECT("host", "username", "password", "db"));