|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2019-08-12 18:55 UTC] damian dot jozwiak dot lodz at gmail dot com
Description:
------------
When class implement an interface it is not possible to override function parameter.
The code works fine if base function is in class
Test script:
---------------
interface Test{
public function f1($param);
}
class inherited implements Test {
public function f1(string $param):\DOMElement{
return new \DOMElement($param);
}
}
$data = new inherited();
$node = $data->f1("node");
var_dump($node->nodeName);
Expected result:
----------------
string(4) "node"
Actual result:
--------------
Fatal error: Declaration of inherited::f1(string $param): DOMElement must be compatible with Test::f1($param)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 17:00:02 2026 UTC |
It's easy to get in a muddle about co- and contravariance, but this error is indeed correct. The promise of the interface is not "I don't care about the type", it's "you can safely pass me any type"; so adding a type constraint ("I only accept string") violates the interface's promise. In technical terms, you are attempting covariance where only contravariance is safe. You might (or might not) find my attempt to demonstrate the concepts with ASCII art interesting: https://github.com/IMSoP/variance-pipes/