title: Access the PHP PDO object in another file
body: <p>I have a class called generic in generic.php. I have a signup.php file which has to perform SQL queries. However, I can't access the PDO object created in generic.php that's stored in the variable $db.</p>
  
  <p>The Generic class looks like this:</p>
  
  <pre><code>class Generic {
      public $db;
  
      public function connect_database() {
          define('USER', 'user');
          define('PASSWORD', 'password');
  
          // Database connection
          try {
              $connection_string = 'mysql:host=localhost;dbname=mydb;charset=utf8';
              $connection_array = array(
                  PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION,
                  PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC
              );
  
              $db = new PDO($connection_string, USER, PASSWORD, $connection_array);
              echo 'Database connection established';
          }
          catch(PDOException $e) {
              $db = null;
          }
      }   
  }
  </code></pre>
  
  <p>I try to access the $db variable (in which the PDO object is stored), but I get an error saying <code>Call to a member function prepare() on a non-object in...</code>. This is how my signup.php file currently looks like:</p>
  
  <pre><code>// Require needed classes
  require_once('generic.php');
  
  // Create needed objects
  $generic = new Generic();
  
  $datetime = date("Y-m-d H:i:s");
  
  try {
      $sql = "INSERT INTO user(
          email, 
          name, 
          username, 
          password
      ) 
      VALUES(
          :email, 
          :name, 
          :username, 
          :password 
      )";
  
      $stmt = $db-&gt;prepare($sql);
  
      $stmt-&gt;bindParam(':email', 'myemail@email.com', PDO::PARAM_STR);       
      $stmt-&gt;bindParam(':name', 'John Doe', PDO::PARAM_STR); 
      $stmt-&gt;bindParam(':username', 'johndow', PDO::PARAM_STR);
      // use PARAM_STR although a number  
      $stmt-&gt;bindParam(':password', 'test123', PDO::PARAM_STR);   
  
      $stmt-&gt;execute();
  } 
  catch(PDOException $e) {
      echo $e;
  }
  </code></pre>
  
  <p>I can't find a way to get the $db variable with the database connection in my signup.php file, so I can execute the query. I've tried <code>$db = $generic-&gt;db</code>, but that doesn't make any difference.</p>
  
  <p>I'm new to OOP PHP and trying some stuff out. I hope this questions explains my problem.</p>