Page 1 of 1
Inheritance - this is a pain!
Posted: Thu Mar 17, 2011 5:05 pm
by cpetercarter
Code: Select all
<?php
abstract class aa
{
abstract public function test();
}
class bb extends aa
{
public function test()
{
$test = $this->getTest();
echo $test;
}
private function getTest()
{
return "This is class bb";
}
}
class cc extends bb
{
private function getTest()
{
return "This is class cc";
}
}
$bb = new bb;
$bb->test();
$cc = new cc;
$cc->test();
// output
// This is class bb
// This is class bb
?>
Class cc inherits the test() function from class bb. However, class cc has its own getTest() method, which overrides the method of the same name in class bb. Or so I thought. But it seems that when I invoke cc::test(), the method calls bb's version of getTest() and not cc's version. In other words, cc inherits the test() method from its parent, but any methods called within the test() method are calls to the parent's methods, not the child's. This is a complete pain. It means that I have to give class cc its own version of test() before it can access its own version of getTest(). Anyone know of a way round this?
Re: Inheritance - this is a pain!
Posted: Thu Mar 17, 2011 5:31 pm
by cpetercarter
OK, I think I have found a solution, but comments would nonetheless be very welcome. It is to make the cc::getTest() methods in both classes protected and not private. I am not completely sure that I follow the logic. It seems that the cc::test() method - inherited from bb - cannot access cc::getTest() if the latter is private, presumably because cc::test() is "really" bb::test(), and so it uses bb:getTest() instead . But bb::getTest() needs to be protected (and not private) too before cc::test() can access cc::getTest(). At which point my brains begin to fry!
Re: Inheritance - this is a pain!
Posted: Thu Mar 17, 2011 9:48 pm
by Weiry
I wish i knew a little more about inheritance than i do... my lecturer a university just bored the hell outa me.
From what i know of inheritance:
protected allows functions to be visible to parents and children.
private disallows any class to see any other classes functions/variables
if cc::getTest() is private, bb::test() can't see the function
if bb::getTest() is private, cc (the child) cant override a parent function it can't see
Re: Inheritance - this is a pain!
Posted: Thu Mar 17, 2011 10:06 pm
by Jonah Bron
@Weiry, 100% correct. Confirmed by tests I ran just now.