I have the following situation: I have a class called primary to which I make an extension to a class called user. In the primary class, I call in a __construct in which I start a connection to mysql , I want to use that connection in my user class to avoid calling it in all my classes, which extends from the primary . I have declared a variable of type protected ($db) for the connection but what is happening to me is that when I try to access my connection from the extended class it sends me the following error:
Fatal error: Call to a member function query() on null in /opt/lampp/htdocs/pendientes/models/usuario_model.php on line 17
Primary Class:
class primary_model {
protected $db;
public $aplicacion;
public function __construct() {
$this->db = classDb::conexion();
$this->aplicacion = array();
}
}
User Class:
class usuario_model extends primary_model {
public function get_usuarionum($search){
$query = $this->db->query("select * from user WHERE 1 ".$search."");
return mysqli_num_rows($query);
}
}
I think you can solve it this way:
Connection Class:
This is your primary model class:
Already in the user class:
That way you could do it, although in my personal opinion I would only use the connection class and it would extend it to the other classes that it is going to use, I also recommend using PDO and prepared statements.
You can also just extend the Connection class in the user class and in the constructor access the
parent::__construct();
entire class you are inheriting in this way.