开发者

Implementing a Shared Prepared SQL statement in PHP

I am writing a class that contains an array of other objects that it generates by querying a database. Each instance of this class runs a nearly identical query so my thought was to setup a shared prepared statement handler and each class would simply bind a different variable to it. Here is the code snippet:

class CQuestion
{
    // this is line 16
    static private $sthAns = SPDO::prepare(
        'SELECT * FROM answers WHERE answers.q_id = :qid'
    );

    // constructor, other functions, etc.   

    private function GetAnswers()
    {
        self::$sthAns->bindParam(':qid', $this->m_iQID, PDO::PAR开发者_如何学CAM_INT);
        self::$sthAns->execute();
    }

}

I know this doesn't work because I get the following error:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in C:\xampp\htdocs\mbtest\CQuestion.php on line 16

Does anyone know a way to implement this without having to reset the prepared statement for each instance of the class?

Incase there is any confusion I have wrapped PDO in my own singleton (SPDO) that sets itself through a ini file. Thats why I am accessing prepare through a static reference.


You can't call a method when instantiating an object/class property. You'll need to use a constructor/initializer for that. Try something like this:

class CQuestion
{
    private static $sthAns;

    private static function getSthAns()
    {
        if (!isset(self::$sthAns)) self::$sthAns = SPDO::prepare(
            'SELECT * FROM answers WHERE answers.q_id = :qid'
        );
        return self::$sthAns;
    }

    private function GetAnswers()
    {
        self::getSthAns()->bindParam(':qid', $this->m_iQID, PDO::PARAM_INT);
        self::getSthAns()->execute();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜