1
You can create a private or protected class in PHP to allow access to its variables and functions only to other specific classes?
Applying: I have a class where I create a connection with the database and wanted to allow access to this class only to other classes that perform CRUD in the database
php connection.
<?php
class Conexao extends Mysqli {
private static $conexao = null;
function Conexao($servidor, $usuario, $senha, $banco) {
parent::__construct($servidor, $usuario, $senha, $banco);
}
public function __destruct() {
self::$conexao->close();
}
public static function getConexao() {
if(!isset(self::$conexao)){
self::$conexao = new Conexao("localhost", "usuario", "senha", "nome_banco");
if (mysqli_connect_error()) {
die('Erro ao conectar ao banco de dados (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
if (false === self::$conexao->set_charset('utf8')) {
die("Error ao usar utf8");
}
}
return self::$conexao;
}
}
php user.
<?php
require_once "conexao.php";
class DAO_usuario {
private $conexao = null;
function __construct() {
$this->conexao = Conexao::getConexao();
}
public function cadastrar_usuario($nome, $usuario, $senha, ...) {
// [...]
}
}
Observing: I neither wear nor will wear frameworks, only pure PHP
The focus of the question is OOP, but it would be interesting to comment on the procedural style equivalent
you can use php extends this way the class will become part of the other one and any class that tries to do include or use name space cannot the code gets more or less like this classBanco extends outraclass >> http://php.net/manual/en/Reflection.extending.php
– Marcos Brinner
@Marcosbrinnerpikatoons in the case then I would
class DAO_usuario extends Conexao
,class DAO_produto extends Conexao
, ...?– Costamilam
Members declared as protected can only be accessed in the reporting class and its heirs classes, those declared as private can only be accessed in the class that defines the private member.
– Fabiano Monteiro
@Fabianomonteiro can exemplify this in a reply?
– Costamilam
So my comment is based on php.net. A full explanation you will find here: http://php.net/manual/en/language.oop5.visibility.php .
– Fabiano Monteiro