I wrote this simple example that demonstrates my problem. I've a Base class and Derived class. When I call derived class's justdoit
function, it doesn't call derived class doer
function, instead it calls base class's doer
function.
Expected output:
Base::doer
Derived::doer
Actual output:
Base::doer
Base::doer
Code:
<?
class Base {
public function justdoit() {
$this->doer();
}
private function doer() {
print "Base::doer\n";
}
}
class Derived extends Base {
private function doer() {
print "Derived::doer\n";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
Here's this same code example in C++ and it works:
class A {
public:
void justdoit();
private:
virtual void doit();
};
void A::justdoit() {
doit();
}
void A::doit() {
std::cout << "A::doit\n";
}
class B : public A {
private:
virtual void doit();
};
void B::doit() {
std::cout << "B::doit\n";
}
int main() {
A a;
B b;
a.justdoit();
b.justdoit();
}
Output:
A::doit
B::doit
Funny thing is if I change my original PHP example and replace private function
with protected function
it starts working:
<?
class Base {
public function justdoit() {
$this->doer();
}
protected function doer() {
print "Base::doer\n";
}
}
class Derived extends Base {
protected function doer() {
print "Derived::doer\n";
}
}
$b = new Base;
$b->justdoit();
$d = new Derived;
$d->justdoit();
?>
Output:
Base::doer
Derived::doer
Does anyone know why PHP and C++ produce different results and why does changing private
to protected
in PHP makes it produce the same result as C++?