Is the code consistent with the Liskov substitution principle?

I am testing my existing PHP5.4 code before updating. I found that the following code no longer works because PHP tightened its inheritance model. Because of this tightening, I read about SOLID , namely, the Liskov Substitution Principle (I am a self-learning programmer) so that I can improve my code and not suffer from future “drags”.

interface IComparable {
    public function equals(self $other);
}

class A implements IComparable{
    protected $var;

    public function __construct($v){
        $this->var=$v;
    }

    public function equals(self $other){
        return ($this->var == $other->var) ? 'equal' : 'different';
    }
}

$a1= new A(7);
$a2= new A(5);
$a3= new A(5);

echo $a1->equals($a2),"\n";
echo $a2->equals($a3),"\n";

php 5.3 result:

  • various
  • equally

php 5.4 result:

PHP Fatal error: A :: equals () declaration must be compatible with IComparable :: equals (IComparable $ other)

I can avoid php5.4 error if I write code as follows:

interface IComparable {
    public function equals($other);
}

class A implements IComparable{
    protected $var;

    public function __construct($v){
        $this->var=$v;
    }

    public function equals($other){
        if(get_class($other) != get_class($this)) return false;
        return ($this->var == $other->var) ? 'equal' : 'different';
    }
}

, , , ? , , , , - 2 OOD?

+5
2

: PHP 5.3 - bug, , .

, LSP 5.3. :

interface IComparable {
    public function equals(self $other);
}

, " IComparable IComparable" ( ). class A LSP, IComparable - , A.

PHP 5.4 LSP, IComparable " " , class A.

5.3, IComparable

interface IComparable {
    public function equals(IComparable $other);
}

class A, , . LSP, .

, , " IComparable , , ", , .

: , , , " ", IComparable , .

IComparable self A::compare(). , , IMHO - ( , ).

+3

, , :

interface IComparable
{
    /** 
     *  @return boolean 
     */
    public function equals(IComparable $other);

    /**
     *  @return mixed
     */
    public function getValue();
}


class A implements IComparable{
    protected $var;

    public function __construct($v){
        $this->var=$v;
    }

    /**
     *  @return mixed
     */
    public function getValue()
    {
       return $this->var;
    }

    /** 
     *  @param  IComparable $other
     *  @return boolean 
     */
    public function equals(IComparable $other)
    {
        return ( $this->getValue() === $other->getValue() );
    }
}

self php , hinting, , .

, , . .

0

All Articles