You can create a static method connection class. So the $mysql
attribute will only be set 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;
to protected static $mysql;
only the classes that are extended to the Connection class that can access this attribute.
So:
class Perguntas extends Conexao{
public function exemplo(){
$mysqli = Conexao::$mysql;
$selecao = $mysqli -> query("SELECT * FROM perguntas");
print_r($selecao);
}
}