views:

57

answers:

1

I'd like to inherit PDOStatement class and use it in my website scripts.

But I am frustrated how to get required object. PDO::query returns only direct PDOStatement object and looks like there are no other method to create PDOStatement object or inherited class.

Initially i thought to move PDOStatement object to constructor of inherit class Something like that:

$stmt = PDO -> query("select * from messages");
$messageCollection = new Messaging_Collection($stmt);

But how to make instance of PDOStatement to inherited object (Messaging_Collection). It is a big question for me.

class Messaging_Collection extends PDOStatement
{
public function __construct(PDOStatement $stmt)
{
//there i should to transform $stmt to $this
// direct $this = $stmt is not possible
// is there other right way?
}
+1  A: 

The simplest way to accomplish what you're trying to do is actually something like this:

class Messaging extends PDO {
    function __construct($dsn="", $username="", $password="", $driver_options=array()) 
    {       
        parent::__construct("mysql:host=" . self::$host_name . ";dbname=" .self::$db_name, self::$username, self::$password, self::$driver_options);
        $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Messaging_Collection', array($this)));
    }
}

Basically, you can use the setAttribute() method to override the default statement class to be used by your custom PDO class.

Noah Goodrich
that is really what i need to do. I know about such possibility for fetching objects, but that was news for me.Thanks
andreyvlru