Using connection obj in another class

Asked

Viewed 121 times

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’t use the object $con and neither $pdo in my class, and I am not allowed to change the connection file. What should I do?

  • You need to import the object in the global scope to the local scope of the method using global

  • Old you’re a genius!

1 answer

0

Nor will I go into too much detail about the real need to use class or to inject dependency into the defined class to properly construct the scope that will be used, because it probably wouldn’t make much sense just looking at a little bit of code from your application. Anyway, if you want to use classes in the best possible way, I recommend to deepen your studies in object orientation.

But to answer the question, the problem with 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 for local scopes, so you will need to do this manually via the directive global:

class Campos
    public function sqlResult($sql){

        global $pdo;

        ...
    }
}

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

What is the difference between global and superglobal variables?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.