note 69369 added to language.oop5.typehinting

From: Date: Sat, 02 Sep 2006 15:59:53 +0000
Subject: note 69369 added to language.oop5.typehinting
Groups: php.notes 
Request: Send a blank email to php-notes+get-116630@lists.php.net to get a copy of this message
The type hinting system can also be used for interfaces. Example: <?php interface fooface { public function foo (); } class fooclass implements fooface { public function foo () { echo ('foo<br>'); } } class barclass implements fooface { public function foo () { echo ('bar<br>'); } } class bazclass implements fooface { public function foo () { echo ('baz<br>'); } } class quuxclass { public function foo () { echo ('quux<br>'); } } function callfoo (fooface $myClass) { $myClass -> foo (); } $myfoo = new fooclass; $mybar = new barclass; $mybaz = new bazclass; $myquux = new quuxclass; callfoo ($myfoo); callfoo ($mybar); callfoo ($mybaz); callfoo ($myquux); // Fails because the quuxclass doesn't implement the fooface interface ?> Using this syntax you can allow a function to work with different classes as long as they all implement the same interfaces. An example might be an online shop that implements a plugin system for payment. If the creator of the script provides a payment module interface then functions can check if it has been implemented in a given payment class. This means that the details of the class are unimportant, so it doesn't matter if it interfaces with PayPal, HSBC, ProTX or any other payment system you care to name, but if it doesn't properly provide all the functionality a payment module requires a fatal error is generated. Unfortunately, it doesn't seem possible to use type hinting with new. In java you could do a "fooface myfoo = new fooclass" which would fail if you tried it with quuxclass instead, but as far as I can tell you can't do a similar test on create with PHP. ---- Server IP: 66.163.161.117 Probable Submitter: 86.1.146.242 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.typehinting.php Edit -- https://master.php.net/note/edit/69369 Del: integrated -- https://master.php.net/note/delete/69369/integrated Del: useless -- https://master.php.net/note/delete/69369/useless Del: bad code -- https://master.php.net/note/delete/69369/bad+code Del: spam -- https://master.php.net/note/delete/69369/spam Del: non-english -- https://master.php.net/note/delete/69369/non-english Del: in docs -- https://master.php.net/note/delete/69369/in+docs Del: other reasons-- https://master.php.net/note/delete/69369 Reject -- https://master.php.net/note/reject/69369 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#116630) next »