EDIT: This question is not a duplicate. Here's why. None of those answers were in the least bit helpful because I completely new to OOP - I need an answer tailored to my level of understanding. Just because the question appears to be similar, the asker is not - not to mention I specifically requested an 'understandable' answer in the first place.
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!