FIRSTLY: This question is not a duplicate. Here's why. My previous question on the topic was closed as a duplicate of this (of all things). That was not in the least bit helpful whatsoever - I didn't understand a damn thing. I'm completely new to OOP - I need an answer tailored to my level of understanding - I had no clue what the answers to the linked questions were talking about. Just because the question appears to be similar, the asker may not be - I specifically requested in my prior question an 'understandable' answer to my level of understanding anyway. So, I'll ask again (and again, if I need to). Here goes:
I'm still reasonably new to PHP overall, and even newer to Object Oriented PHP, having only just started educating myself on it within the past week, and I am still unable to grasp some concepts such as inheritance and what class abstraction is - some of it I've been able to pick up reasonably quickly as I've been working with PDO to handle my database connections and queries for a while now, but otherwise I'm still a newbie at OOPHP, so bear with me if my question seems a bit 'basic'.
I've got an initialization file (init.php) required at the top of each of my webpages, which, among other things, connects to a MySQL database using PDO as such:
try { $dbh = new PDO(conn. data here); } catch(PDOException $e) { echo $e->getMessage(); }
So, as I understand it, on execution of this code, $dbh
is now instantiated as a PDO object. At the bottom of my init.php file is a much of requires linking to function files, such as user.func.php
, images.func.php
, etc.
The problem is whenever I need to query the database from inside one of my functions, I need to declare $dbh
as a global before I'm able to manipulate it, like so:
function myFunction { global $dbh; // Here's the problem! try { $stmt = $dbh->prepare(Some SQL here); $stmt->execute(); } catch { // etc. } }
Now, the problem is not my understanding of why I have to declare as a global - I understand that much, but how I can avoid it. I've read some StackOverflow answers on why to avoid globals, I'm just not sure how.
How would I go about removing global $dbh
from my code? Would I create a database handler class and pass my connection settings to the constructor method each time I instantiate it and use that instead? (Seems a bit redundant).
Not really sure how to replace my use of global variables, so help I can understand is definitely appreciated!