Search code examples
phppdo

VSCode Intelepsense Does not Understand PDOStatement Extend


I'm extending PDO class in my namespace, and adding some extra methods. But intelephense shows undefined method error in Problems section.

This is my class

namespace MyNameSpace;

class PDOStatement extends \PDOStatement {

public $dbh;
protected function __construct($dbh) {
    $this->dbh = $dbh;
}

public function getCol() {
    $this->execute();
    return $this->fetchAll(PDO::FETCH_COLUMN);
}
}

And this is the error message:

Undefined method 'getCol'

And I include my PDOStatement extending class before including my model. (PDOStatement extending class is inside pdo.php)

    include_once(PATH.'/sys/pdo.php');
    include(PATH.'/app/models/mymodel.php');

Extended class works as expected without problem, but intelephense shows errors for all methods I added to PDOStatement class. I'm also extending PDO class, but it works fine (intelephense doesnt show any error for new methods I added to PDO class). I think this is because PDOStatement class is autocreated when you call your pdo->prepare(query), and intelephense does not understand PDOStatement class is extended.

And this is my PDO extending class.

namespace MyNameSpace;
class PDO extends \PDO {
function __construct($dsn, $username="", $password="", $driver_options=array()) {
    parent::__construct($dsn,$username,$password, $driver_options);
    $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('MyNameSpace\PDOStatement', array($this)));
  }
 }

Solution

  • I found the solution by overwriting PDO prepare method. Actually PDO was already using my new PDOStatement but as it is passed as an option, VSCode could not understand it. This is for VSCode to understand the extend, and showing all methods on new Extended PDOStatement Class.

    public function prepare(string $query, array $options = []) : PDOStatement|false
    { 
    
        return parent::prepare($query, $options);
    
    }
    

    Note: The PDOStatement here refers to MyNameSpace\PDOStatement.