When i try to get the returned value of a function in another class i get Undefined Variable. $dbh is null
at my entry point file i instantiate a DB_Functions object:
require_once ('/DB_Functions.php');
$db = new DB_Functions();
this is on DB_Function.php file.
class DB_Functions {
private $db;
public $dbh;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->dbh = $this->db->connect();
}
}
then i use the db object like that:
if ($db->isUserExisted($username)) {}....
The error is inside isUserExisted(...) function. Line 89 is $statement = $dbh....:
public function isUserExisted($username) {
$statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$statement->bindParam(':username', $username);
}
This is in DB_Connect.php file that instantiates the PDO object and returns it
public function connect() {
require_once('config.php');
$dbh = new PDO('mysql:host=' . hostname . ';dbname=' . db_name, username, password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Connected to database';
return $dbh;
}
Error is:
Notice: Undefined variable: dbh in D:\xampp\htdocs\pharm_project\DB_Functions.php on line 89
Line 89 is:
$statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
$dbh = new PDO('mysql:host=' . hostname . ';dbname=' . db_name, username, password);? - castis