我想知道如果我可以在父函数中调用子对象。像这样:在父函数中调用子对象
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。希望这使事情更清晰:)。