Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing return type when overidding a function in the subclass in PHP?

Is this bad? Or this is very common in PHP framework?

For example, in the parent class, there is a save() function which returns the number of rows affected in the database. Then in the child class, I override this function to do some pre-validation, and also would like to simply return a success/failed boolean value.

like image 426
bobo Avatar asked Dec 01 '22 06:12

bobo


1 Answers

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

Here is an illustration how it will be bad:

Let say you have a function that accepts a string and a 'Writer':

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

And here is the original 'Writer' class:

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

What if we pass a 'LazyWriter' instead to the function:

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

The assumption that the return value of the Writer::write() is the number of characters in printThroughWriter has been broken, thus causing inconsistency.

like image 147
Lukman Avatar answered Dec 04 '22 01:12

Lukman