Why is PHP 8.1 telling me that the signature of my function is deprecated?

Viewed 1698

I installed PHP 8.1 but I have an error appear about deprecated function. Do you have an idea about that and to resolve it?

Deprecated: Return type of OM\Db::prepare(string $statement, $driver_options = null) should either be compatible with PDO::prepare(string $query, array $options = []): PDOStatement|false, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in //OM/Db.php on line 114

Line 114

protected ?array $driver_options = null;
protected ?array $options = null;

public function prepare(string $statement, ?array $driver_options = null) //php8
{
  $statement = $this->autoPrefixTables($statement);

  $DbStatement = parent::prepare($statement, \is_array($driver_options) ? $driver_options : []);
  $DbStatement->setQueryCall('prepare');
  $DbStatement->setPDO($this);

  return $DbStatement;
}
1 Answers

PHP 8.1 has added return type declarations to the majority of internal functions/methods. However, as such change would break a lot of existing inheritance, the return types were only specified tentatively. A deprecation notice is raised in all of the cases where the redefined method's signature does not match the signature from the parent class.

In your case, the class extends PDO. You redefine the method prepare but you specify no return value for your method, which defaults to mixed. As mixed is not the same as PDOStatement|false PHP warns you about this inconsistency.

The solution can either be to add the same return type declaration to the redefined method (works only since PHP 8.0 due to union types) or add the temporary attribute to silence the warning. e.g.

#[\ReturnTypeWillChange]
public function prepare(string $statement, ?array $driver_options = null) //php8
{
    // ...

The attribute can be added even if your code supports legacy PHP version. If your code supports only PHP 8.0+ then just add the right return type declaration.

Related