Use function of a class inside another PHP class

3

I have two classes, what is the correct way to call a function from another class, so below error returns

class DB {
public function __construct($user, $password, $database, $host) {
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;

        $this->ConectarBanco();
    }

    protected function ConectarBanco() {
        $this->mysqli = new mysqli($this->user, $this->password, $this->database, $this->host);
        if (mysqli_connect_errno()) {
            die('Não foi possível conectar-se ao banco de dados');
            exit();
        }
    }

    public function FecharBanco() {
        $this->mysqli->close();
    }

    public function ExecutarSQL($sql) {
        $this->result = $mysqli->query($sql);
        return $this->result;
    }

    public function Consultar($dados) {
        $this->newRow = array();
        while($row = $mysqli->fetch_array($dados)) {
            array_push($this->newRow,$this->row);
        }
        return $this->newRow;
    }
}

class Acao{

    public function fnAcao(){

            $query = "SELECT * FROM tabela";

            $result = DB::ConsultarSQL($query);

        return $result;

    }
}
    
asked by anonymous 22.05.2014 / 22:45

2 answers

9

One option would be to instantiate a new object within the class, for example:

class MinhaClasseDois
{
    public function minhaFuncaoDaClasseDois()
    {
        $objeto = new MinhaClasseUm();
        $banana = $objeto->minhaFuncaoDaClasseUm();
    }
}

Without creating a new object, you could use PHP global to refer to an existing instance, but it is not a suitable solution for reusing code:

$instanciaDaClasseUm = new MinhaClasseUm();

class MinhaClasseDois
{
    public function minhaFuncaoDaClasseDois()
    {
        global $instanciaDaClasseUm;
        $banana = $instanciaDaClasseUm->minhaFuncaoDaClasseUm();
    }
}

As I commented , a better option for your particular case would be to do the pass by parameter, which does not need to change almost anything in its original class, requiring only a few settings in fnAcao :

class Acao{
   public function fnAcao($db) {
      $query = "SELECT * FROM tabela";
      $result = $db->ExecutarSQL($query);
      return $result;
   }
}

// Usando a passagem por parâmetro:
$db = new DB( 'Usuario', 'senha123', 'minhaBaseDeDados', 'exemplo.com' );
$db->ConectarBanco(); //Esta linha pode ir para a ação se desejar
$acao = new Acao();
$resultado = $acao->fnAcao($db); //Passando por parâmetro
$db->FecharBanco(); //Esta linha tambem pode ir para a ação se desejar
    
22.05.2014 / 22:51
4

I would use dependency injection in the class you are going to receive the bank class, in the constructor, downloading coupling.

class DBInterface {
    public function ConectarBanco();
    public function FecharBanco();
    public function ExecutarSQL($sql);
    public function Consultar($dados);
}

class DB implements DBInterface{
    private $user;
    private $password;
    private $database;
    private $host;  
    public function __construct($user, $password, $database, $host) {
        $this->user = $user;
        $this->password = $password;
        $this->database = $database;
        $this->host = $host;
        $this->ConectarBanco();
    }
    public function ConectarBanco() {
        $this->mysqli = new mysqli($this->user, $this->password, $this->database, $this->host);
        if (mysqli_connect_errno()) {
            die('Não foi possível conectar-se ao banco de dados');
            exit();
        }
    }
    public function FecharBanco() {
        $this->mysqli->close();
    }
    public function ExecutarSQL($sql) {
        $this->result = $mysqli->query($sql);
        return $this->result;
    }
    public function Consultar($dados) {
        $this->newRow = array();
        while($row = $mysqli->fetch_array($dados)) {
            array_push($this->newRow,$this->row);
        }
        return $this->newRow;
    }
}

class Acao
{
    //INJEÇÃO PELO CONSTRUTOR DA CLASSE
    private $db;
    public function __construct(DBInterface $db){
        $this->db = $db;
    }
    public function fnAcao()
    {
        $query = "SELECT * FROM tabela";
        $result = $this->db->ConsultarSQL($query);
        return $result;
    }
}

Using:

$db        = new DB();
$acao      = new Acao($db); //aqui com injeção
$resultado = $acao->fnAcao();

Although it would indicate a better model for you with a DAL layer, POCO / DTO and Connection each one at your own risk.

Reference:

22.05.2014 / 23:03