Access config variables.php

I'm a beginner in php and I'm having a problem, I have a config file.php like this:

<?php
$config['dbHostname'] = 'localhost';
$config['dbUser'] = 'teste';
$config['dbPassword'] = 'passteste';

Although I have a class with database connection and manipulation functions that would use these variables of config.php but I could not access them in any way, please could someone help me?

Author: Maniero, 2014-04-08

4 answers

Would be one of the forms, in this case by the class constructor.

<?php

$config['dbHostname'] = 'localhost';
$config['dbUser'] = 'teste';
$config['dbPassword'] = 'passteste';

class Conexao
{
    private $pdo;
    public function __construct($config){
        $this->pdo = 
            new PDO("mysql:dbname=generics;host=".$config['dbHostname'], $config['dbUser'], $config['dbPassword']);
    }
}


$conexao = new Conexao($config);

?>
 1
Author: , 2014-05-04 23:24:21

You can access it by declaring the variable at the beginning of the function with the keyword global

public function mostrar1()
{
    global $txt;
    echo $txt;
}

Or use the super-global $GLOBALS

public function mostrar2()
{
    $msg = $GLOBALS['txt'];
    echo $msg;
}

Example running http://ideone.com/ek9ACf

Remembering that if you are programming using classes it is not very recommended to use global variables because they can cause conflicts, if you are using them copy the data from it that interests you and remove it from the global scope.

class Config
{
    /**
     * Configurações
     */
    var $safeconfig;

    public function __construct()
    {
        global $config;

        $this->safeconfig = $config;
        unset($config);
    }

    /**
     * Adicione aqui alguns setters e getters
     * para ter acesso as configurações
     */
}
 1
Author: Cahe, 2014-04-08 03:55:03

A simplified way to do this with config only.php Series:

<?php
    $config['dbHostname'] = 'localhost';
    $config['dbUser'] = 'teste';
    $config['dbPassword'] = 'passteste';
    $config['dbSchema'] = 'baseteste';

    $mysqli = new mysqli($config['dbHostname'],  $config['dbUser'], $config['dbPassword'], $config['dbSchema']);

    if (mysqli_connect_errno()) {
       printf("Falha na conexão: %s\n", mysqli_connect_error());
       exit();
    }

Any doubts about using mysqli function just look at the official documentation

 1
Author: Wilson, 2014-04-08 13:59:01

Hello use this following connection, probably you are not selecting the database use my connection but put the name of your database

<?php 
$servidor = "localhost";
$banco = "NOME DO BANCO DE DADOS AQUI";
$usuario = "teste";
$senha = "passteste";
$conexao = mysql_connect ($servidor, $usuario, $senha);
$conexao = mysql_select_db ("$banco", $conexao);
if (!$conexao) {
echo mysql_error; exit;
}
?>
 0
Author: Lucas C.S, 2014-04-08 03:44:03