note 14167 added to keyword.extends.php
| From: | nigel at mistweb dot net | Date: | Thu, 19 Jul 2001 10:49:40 +0000 |
| Subject: | note 14167 added to keyword.extends.php | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-15574@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());
?>
http://www.php.net/manual/en/keyword.extends.php