note 71141 deleted from language.oop5.typehinting by cmb

From: Date: Sat, 10 Dec 2016 11:53:31 +0000
Subject: note 71141 deleted from language.oop5.typehinting by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208446@lists.php.net to get a copy of this message
Note Submitter: nicholas at nicholaswilliams dot info ---- Please note that the following will not work: <?php abstract class Object { public abstract function toString( ); public abstract function equals( Object &$o ); } class Chair extends Object { public function toString( ) { return 'This is a chair.'; } public function equals( Chair &$o ) { return TRUE; } } class Table extends Object { public function toString( ) { return 'This is a table.'; } public function equals( Table &$o ) { return TRUE; } } $chair = new Chair(); $table = new Table(); echo $chair->equals( $table ); ?> The expected output is "Fatal error: Argument 1 passed to Chair::equals() must be an instance of Chair, called in [filename] on line 38 and defined in [filename] on line 16" but instead you get "Fatal error: Declaration of Chair::equals() must be compatible with that of Object::equals() in [filename] on line 20". This is unlike other OO languages (secifically Java) which not only allow but expect this type of code. It is in the nature of abstraction. However, you can get similar results using the following code instead: <?php abstract class Object { public abstract function toString( ); public abstract function equals( self &$o ); } class Chair extends Object { public function toString( ) { return 'This is a chair.'; } public function equals( self &$o ) { return TRUE; } } class Table extends Object { public function toString( ) { return 'This is a table.'; } public function equals( self &$o ) { return TRUE; } } $chair = new Chair(); $table = new Table(); echo $chair->equals( $table ); ?> This code gives the expected result "Fatal error: Argument 1 passed to Chair::equals() must be an instance of Chair, called in [filename] on line 38 and defined in [filename] on line 16". This is the proper behavior but isn't the most intuitive approach for those of us used to OO programming. Hope this helps someone :-). Nicholas

« previous php.notes (#208446) next »