调用未定义的方法DbConn :: prepare()

时间:2015-09-04 14:25:19

标签: php mysql pdo

尝试PHP OO编程和PDO,我收到错误:

  

调用未定义的方法DbConn :: prepare()

我的两个课程是:

class User {
    public $conn; //db connection

    //contructor - runs code automatically when you create a User object
    function __construct() {
        $this->conn = new DbConn();
    }

    public function Register($username, $email, $name) {     
        //prepared statement + execute
        $stmt = $this->conn->prepare('INSERT INTO users (username, email, name) VALUES (:username,:email,:name)');
        $stmt->execute(array('username' => $username, 'email' => $email, 'name' => $name));

        return true;
    }
}

class DbConn {

    private $username = "root";
    private $password = "password";

    function __construct() {
        try {
            $conn = new PDO('mysql:host=localhost;dbname=oodb', $this->username, $this->password);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            return $conn;

        } catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    } //end contructor

} //end class

我认为我可以将$conn返回给User类,然后在此上调用prepare,但没有运气。

2 个答案:

答案 0 :(得分:2)

按原样保留PDO。它已经是一个班级,请注意,并且非常好。

让你的代码像这样

class User {
    protected $conn; //db connection

    //contructor - runs code automatically when you create a User object
    function __construct($pdo) {
        $this->conn = $pdo;
    }

    public function Register($username, $email, $name) {     
        $stmt = $this->conn->prepare('INSERT INTO users (username, email, name) VALUES (:username,:email,:name)');
        $stmt->execute(array('username' => $username, 'email' => $email, 'name' => $name));
    }
}

$pdo = new PDO('mysql:host=localhost;dbname=oodb', $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$user = new User($pdo);

它可以为您节省很多麻烦。

答案 1 :(得分:-1)

你基本上是在构造函数中返回另一个类对象......这不是这样做的方法

也许您想要的是连接工厂:

class ConnectionFactory{

    /**
     * 
     * @return \PDO
     */
    public static function getConnection(){

        $settings = self::_getSettings();

        return new PDO("{$settings['driver']}:host={$settings['host']};dbname={$settings['dbname']}", $settings['username'], $settings['password']);

    }

    private static function _getSettings(){
        //reads settings from a INI or xml...
    }

}