Changing return type when overriding a function in a subclass in PHP?

This is bad? Or is this very common in the PHP framework?

For example, in the parent class there is a save () function that returns the number of rows affected in the database. Then in the child class, I redefine this function to do some preliminary validation, and also would like to simply return a successful / unsuccessful boolean value.

+3
source share
7 answers

I agree with the consensus that it is bad to change the type (or even the meaning) of the return value.

Here is an illustration of how bad it will be:

, , "Writer":

function printThroughWriter(String $text, Writer $writer) {
    $count = $writer->write($text);
    print "Writer '".get_class($writer)."' printed $count characters.";
}

"Writer":

class Writer {
    public function write(String $text) {
        print $text;
        return strlen($text);
    }
}

, "LazyWriter" :

class LazyWriter extends Writer {
    public function write(String $text) {
        return true;
    }
}

, Writer::write() - printThroughWriter, , .

+5

, . , . UNLESS, ( ).

.

+3

, .

, , ( ).

+3

PHP , , , .

. , , , , . , - , , - . , .

, , .

+2

, .

, , pass-by-reference. , , .

+2

, . , : " , myCollection.add() - ? , ! m , !"

+2

, , .

, overriding , 0 return , FALSE, TRUE . - , - (===) , , () FALSE, 0 .

In your example, the return type of the return is not more specific than the type of the overridden return, so you should not do this.

+1
source

Source: https://habr.com/ru/post/1723739/


All Articles