使用PDO调用PHP静态函数

时间:2014-04-24 16:09:48

标签: php class pdo static extends

我的数据库 Database.php

有一个Abstract类
abstract class Database {
private $host      = DB_HOST;
private $user      = DB_USER;
private $pass      = DB_PASS;
private $dbname    = DB_NAME;

private $dbh;
private $error;

private $stmt;

public function __construct(){        
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(            
        PDO::ATTR_PERSISTENT    => true,
        PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION            
    );
    // Create a new PDO instanace
    try{
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch(PDOException $e){
        $this->error = $e->getMessage();
    }
}

public function query($query){        
    $this->stmt = $this->dbh->prepare($query);
    }
}

然后我有一个 Recipe类,它使用静态函数扩展 Database

class Recipe extends Database{

private $id;
private $slug;
private $title;     

public function __construct {
       $this->id=$id;
       $this->slug=$slug;
   $this->title=$title;
       parent::__construct();
    }

    public static function getAll () {      

   self::query('select * from recipes order by id');        
   $rows = self::resultset();       
   $recipes=array();
   foreach ($rows as $row){// show}
    }

最后在我的index.php中:

$recipes=Recipe::getAll();

这样做的正确方法是什么?

每次我需要像这样的方法进行SQL查询时,我不想创建Recipe的实例:

$recipes=new Recipe();
$recipes->getAll();

然后在食谱类中:

$this->query('select * from recipes order by id');      
$rows = $this->resultset();

谢谢!

0 个答案:

没有答案