ds0802 2011-01-27 21:10
浏览 43
已采纳

在PHP中实现Shared Prepared SQL语句

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::PARAM_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.

  • 写回答

1条回答 默认 最新

  • dsa88886666 2011-01-27 21:26
    关注

    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();
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥50 用AT89C52单片机设计一个温度测量与控制电路
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题