note 14167 deleted from keyword.extends by jimw
| From: | jimw@php.net | Date: | Fri, 07 Dec 2001 20:35:58 +0000 |
| Subject: | note 14167 deleted from keyword.extends by jimw | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-21936@lists.php.net to get a copy of this message | ||
Polymorphism is alive and well in PHP! The following shows many examples and variations that work,
and many more combinations are possible.
<?php
//(save this file as poly.php to test it)
class Flow {
var $linkStr = "not set";
function getLink() {
return $this->linkStr;
}
}
class A_flow extends Flow {
function A_flow() {//sets superclass' variable
$this->linkStr = '<a href="poly.php?type=A">Click here for an
A</a>';
}
}
class B_flow extends Flow {//overrides superclass' variable
var $linkStr = '<a href="poly.php?type=B">Click here for a B</a>';
}
class C_flow extends Flow {
function getLink() {//overrides superclass' method
return '<a href="poly.php?type=C">Click here for a C</a>';
}
}
class View {
var $flow;
function View ($flowObj) {
$this->flow = &$flowObj; //N.B. weakly typed language: needs self-discipline!
}
function display($newFlowObj = false) {
if ($newFlowObj) $this->flow = &$newFlowObj;
//polymorphic call to correct version of getLink():
echo '<p>That which you sow, so shall you reap: ' . $this->flow->getLink() .
"\n";
}
}
if ($type) echo "<p>You have been given a $type\n";
$viewA = new View (new A_flow());
$viewB = new View (new B_flow());
$viewA->display();
$viewB->display();
$viewB->display(new C_flow());
?>