Leonard H Leonard H - 5 months ago 43
PHP Question

Declaration of class must be compatible with interface

Comparare.php
<?php
interface Comparare{
public function compara(self $a);
}
?>

clasa.php
<?php
class Clasa implements Comparare{
public $v;
public function compara(self $a){
if($this->v < $a->v)
{
return -1;
}
else if($this->v==$a->v)
{
return 0;
}
else
{
return 1;
}
}
function __construct($a){
$this->v=$a;
}
}
?>
test.php
<?php
function __autoload($class_name){
require_once ($class_name) . ".php";
}
function maxim(Comparare $a,Comparare $b){
if ($a->compara($b)<0){
return $b;
}
else {
return $a;
}
}
$x=new Clasa(7);
$y=new Clasa(8);
$max=maxim($x,$y);
echo "maximul este:" . $max;
?>



Fatal error: Declaration of Clasa::compara() must be compatible with
Comparare::compara(Comparare $a) in
D:\xammp\htdocs\php\clase\comparare\clasa.php on line 3


I use XAMPP 3.2.2( PHP Version 5.5.33 )

Answer

The self type in your interface refers to the interface - in your class it refers to the class. Those are two different types. You need to use the interface type name when defining the method in order for the types to match. When implementing an interface method, the signature, including the types, has to match for the implementation to be picked up.

public function compara(Comparare $a) {
Comments