note 69369 deleted from language.oop5.typehinting by cmb

From: Date: Sat, 10 Dec 2016 11:45:36 +0000
Subject: note 69369 deleted from language.oop5.typehinting by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208441@lists.php.net to get a copy of this message
Note Submitter: ---- 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.

« previous php.notes (#208441) next »