我想知道如果我可以在父函數中調用子對象。像這樣:在父函數中調用子對象
class Parent {
public function A() {
<< I want to call the object here >>
// Some code
}
}
Class Child extends Parent {
public function B() {
// Some code
}
}
$Child = new Child();
$Child -> B();
這兩個類在不同的文件中。 My Child類正在使用函數B()與我的數據庫建立連接。在我父類的A()中,我試圖插入填充表單時收到的數據,但我需要連接到數據庫,我不知道如何調用該對象。注意:當我在同一個類中有兩個函數時,我的代碼正在工作。
我沒有找到解決辦法,所以我會嘗試後我的實際代碼:
class db_connect extends Model
{
private $dbname = "...";
private $dbuser = "...";
private $dbpass = "...";
private $dbhost = "...";
public $dbc;
public function Connect()
{
$this->dbc = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($this->dbc === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}}
}
因此,這是從上面和connect()類兒童被B()。
現在父
class Model
{
public $query;
public $result;
public function proccess_data($marca,$model,$pret,$descriere){
<< I am trying to make a connection here from config.php using the function Connect() >>
$this->query = "INSERT INTO autoturisme (autoturism_id, marca, model, pret, descriere) " .
"VALUES (NULL, '$marca', '$model', '$pret', '$descriere')";
$this->result = mysqli_query(<<Also here I would need the connection>>, $this->query)
or die(mysqli_error(<<And here>>));
if($this->result == 1){
echo "<br/>Your data were processed";
} else {
echo "<br/>We are sorry but an error occurred";
}
$this->close_db();
}
在mysqli_query我需要一個參數作爲mysqli的,這是我的數據庫的連接。該參數位於子級,$ dbc,它在Connect()函數中調用:$ this-> dbc。同樣適用於mysqli_error。希望這使事情更清晰:)。