PHP Variable Scope PDO Connection

  mysql, pdo, php

I have the following config file which holds the DSN details:

<?php
//Database Parameters
define('DB_HOST', 'localhost');
define('DB_USER', 'user');
define('DB_PASS', 'pass');
define('DB_NAME', 'testdb');

When I was using this class to connect to the db, everything worked.

<?php 
class Data {
    private $dbHost = DB_HOST;
    private $dbUser = DB_USER;
    private $dbPass = DB_PASS;
    private $dbName = DB_NAME;

    private $dbh;
    private $err;
    private $pdo;


    public function __construct() {
        $dsn = 'mysql:host=' . $this->dbHost . ';dbname=' . $this->dbName;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try {
            $this->dbh = new PDO($dsn, $this->dbUser, $this->dbPass, $options);
        } catch (PDOException $e) {
            $this->err = $e->getMessage();
            echo $this->err;
        }
        return $this->pdo;
    }
}

When I tried to improve my code adn switched to this connection class, my config stopped passing:

<?php 

class DBConnection {
    private $dbHost = DB_HOST;
    private $dbUser = DB_USER;
    private $dbPass = DB_PASS;
    private $dbName = DB_NAME;

    public static function make() {
        $dsn = 'mysql:host=' . $dbHost . ';dbname=' . $dbName;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try {
            return new PDO($dsn, $dbUser, $dbPass, $options);
        }   catch(PDOException $e) {
                die($e->getMessage());
            }
    }
}

?>

I even tried to change the variables to public but it changed nothing. What is wrong with this and is there a better way? Is it better to use a constructor instead of method?

I am getting an Undefined Variable but I have defined the DSN variables in the config file…. I am not sure what I am missing. Any pointers would be very much appreciated.
Thanks,

Source: Ask PHP

LEAVE A COMMENT