note 116233 added to language.oop5.interfaces

From: Date: Thu, 27 Nov 2014 04:37:58 +0000
Subject: note 116233 added to language.oop5.interfaces
Groups: php.notes 
Request: Send a blank email to php-notes+get-201025@lists.php.net to get a copy of this message
Just wrote some examples of duck-typing in PHP. Sharing here. <?php /** * An example of duck typing in PHP */ interface CanFly { public function fly(); } interface CanSwim { public function swim(); } class Bird { public function info() { echo "I am a {$this->name}\n"; echo "I am an bird\n"; } } /** * some implementations of birds */ class Dove extends Bird implements CanFly { var $name = "Dove"; public function fly() { echo "I fly\n"; } } class Penguin extends Bird implements CanSwim { var $name = "Penguin"; public function swim() { echo "I swim\n"; } } class Duck extends Bird implements CanFly, CanSwim { var $name = "Duck"; public function fly() { echo "I fly\n"; } public function swim() { echo "I swim\n"; } } /** * a simple function to describe a bird */ function describe($bird) { if ($bird instanceof Bird) { $bird->info(); if ($bird instanceof CanFly) { $bird->fly(); } if ($bird instanceof CanSwim) { $bird->swim(); } } else { die("This is not a bird. I cannot describe it."); } } // describe these birds please describe(new Penguin); echo "---\n"; describe(new Dove); echo "---\n"; describe(new Duck); ---- Server IP: 72.52.91.14 Probable Submitter: 202.130.124.18 ---- Manual Page -- http://php.net/manual/en/language.oop5.interfaces.php Edit -- https://master.php.net/note/edit/116233 Del: integrated -- https://master.php.net/note/delete/116233/integrated Del: useless -- https://master.php.net/note/delete/116233/useless Del: bad code -- https://master.php.net/note/delete/116233/bad+code Del: spam -- https://master.php.net/note/delete/116233/spam Del: non-english -- https://master.php.net/note/delete/116233/non-english Del: in docs -- https://master.php.net/note/delete/116233/in+docs Del: other reasons-- https://master.php.net/note/delete/116233 Reject -- https://master.php.net/note/reject/116233 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201025) next »