Re: Why is polymorphism in PHP not like other languages? Is there a bug in PHP? [message #185128 is a reply to message #185102] |
Thu, 27 February 2014 20:08 |
kurtk(at)pobox(dot)com
Messages: 10 Registered: May 2012
Karma:
|
Junior Member |
|
|
Thanks for all the replies. I could probably have simplified the example, like this
<?php
class Base {}
class DerivedCommonBase extends Base {
public function whoami() { echo "I am DerivedCommonBase\n"; }
}
class Derived1 extends Base {
public function whoami() { echo "I am Derived1\n"; }
}
class Derived2 extends Base {
public function whoami() { echo "I am Derived2\n"; }
}
// Base has not whoami() method...
function test(Base $b) { $b->whoami(); }
$b = new Base();
$d1 = new Derived1();
$d2 = new Derived2();
$a = array();
$a[] = $d1;
$a[] = $d2;
foreach($a as $x) {
echo test($x);
}
test($d1);
test($d2);
test($b); // <--...this is detected at run time
However, I did learn that in PHP you can pass a derived class to a method that takes a base class and then invoke a method that does not exist in the base class. Derived1 is a DerivedCommonBase is a Base. Something with Derived2. But somehow PHP knows the final subtype $b within method test(Base $b)..
|
|
|