You can create a connection class with static method. So the attribute $mysql
will be configured only once and can be used by other classes.
Class Conexao.php
class Conexao{
public static $mysql;
function __construct(){
$this::setSql();
}
static function setSql(){
self::$mysql= new mysqli('p:localhost','root','','game');
}
}
Class Perguntas.php
class Perguntas{
public function exemplo(){
$mysqli = Conexao::$mysql;
$selecao = $mysqli -> query("SELECT * FROM perguntas");
print_r($selecao);
}
}
index php.
include("Conexao.php");
include("Perguntas.php");
new Conexao();
$perguntas = new Perguntas();
$perguntas -> exemplo();
The created attribute is public, but if you change it from public static $mysql;
for protected static $mysql;
only classes that are extended to the Connection class that can access this attribute.
Thus:
class Perguntas extends Conexao{
public function exemplo(){
$mysqli = Conexao::$mysql;
$selecao = $mysqli -> query("SELECT * FROM perguntas");
print_r($selecao);
}
}
You have to make a class that has the responsibility to connect to the database.
– Roberto de Campos