Including parent objects in "require"d files
<h2>Overview</h2>

<p>I connect to a database in <code>index.php</code>, then import my <code>classes.php</code> file using <code>require_once()</code>. However, when connecting to the database, the database connection is undefined.</p>

<h2>Code</h2>

<p><code>index.php</code></p>

<pre><code>$dbh = new PDO("mysql:host=$hostname;dbname=$dbname",$username,$password);
require_once("inc/classes.php");

/* ..... */

if($_POST["form"]=="login"){

    //Retrieve values
    $e = $_POST["email"];
    $p = $_POST["password"];

    //Data validation
    if(!filter_var($e, FILTER_VALIDATE_EMAIL)||strlen($e)&lt;3) $errors-&gt;addError("email", "Please enter a valid email address.");
    if(strlen($p)&lt;1) $errors-&gt;addError("password", "Please enter a valid password");
    $errors-&gt;killErrors();

    //Log user in
    $user = new User($e);
    if(!$user-&gt;login($p)) $errors-&gt;addError("form", "Incorrect username or password.");
    $errors-&gt;killErrors();

    exit("success");
}
</code></pre>

<p><code>inc/classes.php</code></p>

<pre><code>class User
{
    public $id, $email, $data;

    public function __construct($e = null){

        if(isLoggedIn()){
            $stmt = $dbh-&gt;prepare("SELECT * FROM `users` WHERE `id`=? LIMIT 1");
            $stmt-&gt;execute(array($_SESSION["userid"]));
            $this-&gt;data = $stmt-&gt;fetch(PDO::FETCH_ASSOC);
        } else $this-&gt;email = $e;

    }

    public function login($p){
        //Perform database query for user
        $stmt = $dbh-&gt;prepare("SELECT `id`, `password` FROM `users` WHERE `email`=? LIMIT 1");
        $stmt-&gt;execute(array($this-&gt;email));
        if($stmt-&gt;rowCount()&lt;1) return false;

        //Check password is correct
        $data = $stmt-&gt;fetch(PDO::FETCH_ASSOC);
        if(!password_verify($p, $data["password"])) return false;

        if(!$this-&gt;email) exit("User can only be logged in with an email address, not by User ID");

        $this-&gt;id = $data["id"];
        return $this-&gt;validate($this-&gt;id) ? true : false;
    }

}
</code></pre>

<h2>Output</h2>

<blockquote>
  <p><strong>Notice:</strong> Undefined variable: dbh in <strong>/var/www/html/foo/public_html/bar/inc/classes.php</strong> on line <strong>80</strong></p>
  
  <p><strong>Fatal error:</strong> Call to a member function prepare() on null in <strong>/var/www/html/foo/public_html/bar/inc/classes.php</strong> on line <strong>80</strong></p>
</blockquote>

<p>Line 80 is:</p>

<pre><code>$stmt = $dbh-&gt;prepare("SELECT `id`, `password` FROM `users` WHERE `email`=? LIMIT 1");
</code></pre>

<h2>Question</h2>

<p>How can I include the database connection in <code>index.php</code> and have the <code>classes.php</code> file accept that PDO object?</p>