I would like to know If I can call a child's object in a parent function. Like this:
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();
The two classes are in different files. My Child class is making a connection with my database with function B(). In my Parent's class, A(), I am trying to insert data I receive from filling a form, but I need a connection to the database and I do not know how I can call that object. Note: My code is working when I have both functions in the same Class.
I did not find the solution, so I will try and post my real code:
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());
}}
}
So this was the Class Child from Above and Connect() was B().
Now the parent
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();
}
In the mysqli_query I need a parameter as a mysqli, which is the connection to my database. The parameter is in the Child's Class, $dbc, and it is called in the function Connect() with: $this->dbc . Same goes for mysqli_error. Hope this makes things clearer :).
Aucun commentaire:
Enregistrer un commentaire