doc-en icon indicating copy to clipboard operation
doc-en copied to clipboard

PDOException property $code of type string not int

Open 2m5g opened this issue 2 years ago • 1 comments

I've stumbled across it a few times now that when catching a \PDOException and dumping the code from the exception via getCode() method that the return value seems to be of type string.

Example:

// some syntax error in SQL Query
catch(\PDOException $e) {
    var_dump($e->getCode()); //Output: string(5) "42000"
}

Documentation mentions return type int (see https://www.php.net/manual/en/class.pdoexception.php):

class PDOException extends RuntimeException {
    /* Properties */
    // ...
    /* Inherited properties */
    // ...
    protected int $code;

// ...

As per zend_exceptions.stub.php the property $code of the Exception class is marked with TODO (see https://github.com/php/php-src/blob/7684a3d138f793630e2ac640ac7d3acc4a79467b/Zend/zend_exceptions.stub.php#L37 ):

protected $code = 0;  // TODO add proper type (i.e. int|string) 

Further within zend_exceptions.stub.php no return type is declared for the getCode() method (see https://github.com/php/php-src/blob/7684a3d138f793630e2ac640ac7d3acc4a79467b/Zend/zend_exceptions.stub.php#L53 ):

   /**
     * @return int
     * @implementation-alias Exception::getCode
     */
    final public function getCode() {} 

Additionally I'd like to quote Core_c.php in getCode() of JetBrains PhpStorm which also mentions the same:

Gets the Exception code Returns: int|mixed the exception code as integer in Exception but possibly as other type in Exception descendants (for example as string in PDOException). Links: https://php.net/manual/en/exception.getcode.php

2m5g avatar Dec 07 '23 20:12 2m5g

Related to https://github.com/php/php-src/issues/9529

Girgias avatar Dec 27 '23 01:12 Girgias