FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Why is polymorphism in PHP not like other languages? Is there a bug in PHP?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
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 Go to previous messageGo to previous message
kurtk(at)pobox(dot)com is currently offline  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)..
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Completely stumped
Next Topic: Correlating curl resources to some other object.
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Sun Nov 24 23:33:20 GMT 2024

Total time taken to generate the page: 0.04229 seconds