Using connection obj in another class

1
<?php
ob_start();
# Dados de Conexão com o Banco de dados Principal
$con_bd[banco]  =   "teste";
$con_bd[login]  =   "teste";
$con_bd[senha]  =   "teste";
$con_bd[server] =   "teste";
$error          =   "";

$con    =   mysql_connect($con_bd[server],$con_bd[login],$con_bd[senha]);

if (!$con) {
    $error = "Falha ao estabelecer uma conexao com o banco de dados!";
} else {
    mysql_select_db($con_bd[banco],$con); 
}


//Realiza a Conexão com o Banco de Dados via PDO   
if(is_null($pdo)){
    $dsn = "mysql:host=".$con_bd[server].";dbname=".$con_bd[banco];
    try{
        $pdo = new PDO($dsn, $con_bd[login], $con_bd[senha]);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }catch(PDOException $e){
        $error = "Falha ao estabelecer uma conexao com o banco de dados!";
    }
}

ob_end_clean();

echo $error;
?>

Another file:

namespace classes\relatorio\classes;

$nivel = str_repeat("../",3);

include ($nivel.'files/conecta.php');
include ($nivel.'files/funcoes.php');


class Campos

    public function sqlResult($sql){

                    $sql = $pdo->query($sql);
                            if($sql->rowCount() > 0) {
                    }

Even using Use or Include I can not use the object $con and nor $pdo in my class, and I am not allowed to change the connection file. What should I do?

    
asked by anonymous 21.08.2017 / 20:39

1 answer

0

I will not go into too much detail about the real need to use class or to do dependency injection in the defined class to properly build the scope that will be used, because probably this would not even make much sense just by seeing a small snippet of code of its application. Anyway, if you want to use classes in the best way possible, I recommend to further study your studies in object orientation.

But, answering the question, the problem in your code is the scope. You are, within the class method, trying to access an object that belongs to the global scope. PHP, by default, does not import global variables into local scopes, so you'll need to do this manually using the global directive:

class Campos
    public function sqlResult($sql){

        global $pdo;

        ...
    }
}

I answered something about the PHP global variables in this question:

What's the difference between global and superglobal variables?

    
21.08.2017 / 23:11