Note that there are some explanatory texts on larger screens.

plurals
  1. POAvoiding use of a global database handler variable in PHP, to someone who is new to OOP?
    text
    copied!<p><strong>EDIT:</strong> This question is <strong>not</strong> 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 <strong>appears</strong> to be similar, the asker is not - not to mention I specifically requested an 'understandable' answer in the first place. </p> <hr> <p>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'.</p> <p>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:</p> <pre> try { $dbh = new PDO(conn. data here); } catch(PDOException $e) { echo $e->getMessage(); } </pre> <p>So, as I understand it, on execution of this code, <code>$dbh</code> 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 <code>user.func.php</code>, <code>images.func.php</code>, etc. </p> <p>The problem is whenever I need to query the database from inside one of my functions, I need to declare <code>$dbh</code> as a global before I'm able to manipulate it, like so:</p> <pre> function myFunction { global $dbh; // Here's the problem! try { $stmt = $dbh->prepare(Some SQL here); $stmt->execute(); } catch { // etc. } }</pre> <p>Now, the problem is not my understanding of <strong>why</strong> 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. </p> <p>How would I go about removing <code>global $dbh</code> 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).</p> <p>Not really sure how to replace my use of global variables, so help I can understand is definitely appreciated! </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload