title: PHP variable scope: passing external objects to a class
body: <p>I'm defining models that share a common database. However, I'm having trouble passing a PDO object via <code>require_once()</code>. I'm getting the following error:</p>
  
  <pre><code>Fatal error: Call to a member function prepare() on a non-object...
  </code></pre>
  
  <p>I'm guessing this is just a scope issue. I tried declaring <code>$database</code> as a <code>global</code> in both files but that didn't seem to work. Any ideas?</p>
  
  <p><strong>common.php</strong></p>
  
  <pre><code>$host = 'localhost';
  $dbname = 'database';
  $username = 'user';
  $password = 'pass';
  
  $database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT =&gt; true));
  </code></pre>
  
  <p><strong>product.php</strong></p>
  
  <pre><code>require_once('common.php');
  
  class Product {
  
    function fetch_from_category($category) {
      $query = $database-&gt;prepare('SELECT * FROM product WHERE product.category = ?');
      $query-&gt;execute($category);
      return $query-&gt;fetchAll(PDO::FETCH_ASSOC);
    }
  
  }
  </code></pre>