I have two classes: The first is called "MySQL" and contains all the functions for the queries (in addition to the ones that the API "MySQLi" brings.) Use __construct to create the MySQLi object. The second (Users), which is the daughter of the previous one, uses a __construct to instantiate other necessary classes.
When using __construct in the "Users" class, it returns an error: Fatal error: Uncaught Error: Call to a member function query () on null in D: \ Lautaro \ Applications \ Programs \ Xampp \ htdocs \ src \ classes \ MySQL.php.
If I delete __construct and its sentences, the error is solved, but I need YES or SI to make those instances.
MySQL.php
namespace Brax\BBDD;
require_once $_SERVER['DOCUMENT_ROOT'].'/config/cfg.php';
class MySQL {
private $server;
private $username;
private $password;
private $database;
public $mysqli; // Ver si la visibilidad afecta a los traits
public function __construct() {
$this->server = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'db';
$this->mysqli = new \mysqli($this->server, $this->username, $this->password, $this->database);
$this->mysqli->set_charset('utf8');
}
/**
* This function will make a query to the DB.
* @param string $sql [It's a SQL string]
* @return object|false [If succesfull, it will return an object, else, it will return false]
*/
protected function query(string $sql) {
if (!empty($sql)) {
if ($response = $this->mysqli->query($sql)) {
if (DEBUG === true) {
echo '['.HOUR.'] MySQLi query() DEBUG [SQL Executed]: '.$sql.PHP_EOL;
}
return $response;
} else {
if (DEBUG === true) {
echo '['.HOUR.'] MySQLi query() DEBUG [SQL Executed with ERROR * ]: '.$sql.PHP_EOL;
}
return false;
}
} else {
if (DEBUG === true) {
echo '['.HOUR.'] MySQLi Query DEBUG [SQL]: The query is empty.'.PHP_EOL;
}
return false;
}
}
Users.php
namespace Brax\Usuarios;
require_once $_SERVER['DOCUMENT_ROOT'].'/config/cfg.php';
spl_autoload_register('Brax\autoload');
class Usuarios extends \Brax\BBDD\MySQL {
use \Brax\Traits\CRUDTrait;
private $Panel,
$Accesos,
$Referidos,
$GameServers;
public function __construct() {
$this->Panel = new \Brax\Panel\Panel();
$this->Accesos = new Accesos\Accesos();
$this->Referidos = new \Brax\Referidos\PostsReferidos();
$this->GameServers = new \Brax\GameServers\GameServers();
}
}
The Users class should work with __construct, and not return the error explained above.