Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending PDO Statement Class

Tags:

php

pdo

Is it possible to extend PHP PDO statement class to add custom methods to it? This would be different from extending the base PDO class. If so, how would one go about doing it since the statement class is only returned when running queries through the PDO class?

like image 608
Levi Hackwith Avatar asked Aug 07 '10 17:08

Levi Hackwith


People also ask

What is a PDO statement?

PDO (PHP Data Objects) is an abstraction layer for your database queries and is an awesome alternative to MySQLi, as it supports 12 different database drivers. This is an immense benefit for people and companies that need it. However, keep in mind that MySQL is by far the most popular database.

What is PDOStatement class?

The PDOStatement class ¶Represents a prepared statement and, after the statement is executed, an associated result set.

What is PDOStatement PHP?

PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way to access databases. This means developers can write portable code much easier. PDO is not an abstraction layer like PearDB. PDO is a more like a data access layer which uses a unified API (Application Programming Interface).

What is PDO in PHP with example?

PDO—PHP Data Objects—are a database access layer providing a uniform method of access to multiple databases. It doesn't account for database-specific syntax, but can allow for the process of switching databases and platforms to be fairly painless, simply by switching the connection string in many instances.


2 Answers

You can set the class with PDO::setAttribute():

PDO::ATTR_STATEMENT_CLASS: Set user-supplied statement class derived from PDOStatement. Cannot be used with persistent PDO instances. Requires array(string classname, array(mixed constructor_args)).

Example:

$pdo->setAttribute(PDO::ATTR_STATEMENT_CLASS, [Custom::class]);
like image 173
Gordon Avatar answered Sep 23 '22 00:09

Gordon


This is answered by a user in the PHP Manual under PDO:

class Database extends PDO {
    function __construct($dsn, $username="", $password="", $driver_options=array()) {
        parent::__construct($dsn,$username,$password, $driver_options);
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement', array($this)));
    }
}
class DBStatement extends PDOStatement {
    public $dbh;
    protected function __construct($dbh) {
        $this->dbh = $dbh;
    }
}

You can find his original answer by searching: 'smileaf' at this page: https://php.net/manual/en/book.pdo.php

like image 37
iateadonut Avatar answered Sep 24 '22 00:09

iateadonut