0

I'm defining models that share a common database. However, I'm having trouble passing a PDO object via require_once(). I'm getting the following error:

Fatal error: Call to a member function prepare() on a non-object...

I'm guessing this is just a scope issue. I tried declaring $database as a global in both files but that didn't seem to work. Any ideas?

common.php

$host = 'localhost';
$dbname = 'database';
$username = 'user';
$password = 'pass';

$database = new PDO("mysql:host=$host;dbname=$dbname", $username, $password, array(PDO::ATTR_PERSISTENT => true));

product.php

require_once('common.php');

class Product {

  function fetch_from_category($category) {
    $query = $database->prepare('SELECT * FROM product WHERE product.category = ?');
    $query->execute($category);
    return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}
1
  • 1
    $database is defined outside the class; and, similar to normal functions, you can't see the variable inside a class. Either pass it to the class as MrCode suggested or set it as global ( not recommended though ) as Rawkode suggested. Commented Nov 27, 2012 at 12:42

2 Answers 2

1

It is indeed a scope issue, $database is not defined inside Product::fetch_from_category. You should pass it into the object when instantiating it:

class Product {

  protected $database;

  public function __construct(PDO $database) {
      $this->database = $database;
  }

  public function fetch_from_category($category) {
      $query = $this->database->prepare('SELECT * FROM product WHERE product.category = ?');
      $query->execute($category);
      return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}

...

require_once 'common.php';
require_once 'product.php';

$product = new Product($database);
Sign up to request clarification or add additional context in comments.

Comments

1

Pass $database to the class, then store it as a property and access with $this->database:

class Product {

  protected $database;

  public function setDb($db)
  {
      $this->database = $db;
  }

  function fetch_from_category($category) {
    $query = $this->database->prepare('SELECT * FROM product WHERE product.category = ?');
    $query->execute($category);
    return $query->fetchAll(PDO::FETCH_ASSOC);
  }

}

$p = new Product();
$p->setDb($database);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.