note 71141 added to language.oop5.typehinting

From: Date: Mon, 13 Nov 2006 20:53:52 +0000
Subject: note 71141 added to language.oop5.typehinting
Groups: php.notes 
Request: Send a blank email to php-notes+get-119685@lists.php.net to get a copy of this message
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 ---- Server IP: 216.194.113.175 Probable Submitter: 69.180.200.126 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.typehinting.php Edit -- https://master.php.net/note/edit/71141 Del: integrated -- https://master.php.net/note/delete/71141/integrated Del: useless -- https://master.php.net/note/delete/71141/useless Del: bad code -- https://master.php.net/note/delete/71141/bad+code Del: spam -- https://master.php.net/note/delete/71141/spam Del: non-english -- https://master.php.net/note/delete/71141/non-english Del: in docs -- https://master.php.net/note/delete/71141/in+docs Del: other reasons-- https://master.php.net/note/delete/71141 Reject -- https://master.php.net/note/reject/71141 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119685) next »