Using PDO database class within other PHP classes
<p>I have a database class that uses PDO. Here's a portion example of it:</p>

<pre><code>class db {
private $host;
private $username;
private $password;
private $con;
    private $pdo;

public function __construct( $database = "dnname" )
{
    $this-&gt;host = "localhost";
    $this-&gt;username = "username";
    $this-&gt;password = "pass";
            $conStr = "host={$this-&gt;host};dbname={$database}";
            try {
                $this-&gt;pdo = new PDO( "mysql:$conStr", $this-&gt;username, $this-&gt;password );
                $this-&gt;pdo-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            }
            catch( PDOException $e ) {
                echo "error ". $e-&gt;getMessage();
            }
}

public function fetch_single_row($sql, $data)
{
    if( $data !== null )
        $data = array_values( $data ); // Incase it's an associative array
    $sel = $this-&gt;pdo-&gt;prepare( $sql );
    $sel-&gt;execute( $data );
    $sel-&gt;setFetchMode( PDO::FETCH_OBJ );
    $obj = $sel-&gt;fetch();
    return $obj;
}
</code></pre>

<p>I would like to use this class and its functions (it has more than I've included) inside other classes. </p>

<p>I have tried many many different things, but the only thing <em>that works</em> so far is starting a new instance of db in every new class which <strong>I think is bad practice</strong>. For instance:</p>

<pre><code>class cms {
   function cms(){
       $this-&gt;db = new db();
   }

   function is_admin($id) {
    if($this-&gt;db-&gt;fetch_single_row("SELECT id FROM user WHERE id = ? LIMIT 1", array($id))){
        return true;
    } else {
        return false;
    }
}
</code></pre>

<p>in my index.php, I include these classes and use them:</p>

<pre><code>include("db.class.php");
include("cms.class.php");

$cms = new cms();

if($cms-&gt;is_admin($id)){
   //code here
}
</code></pre>

<p>What is the correct way to accomplish this?</p>
