【发布时间】:2015-10-09 00:07:41
【问题描述】:
我写了这个简单的例子来演示我的问题。我有一个基类和派生类。当我调用派生类的justdoit函数时,它不会调用派生类的doer函数,而是调用基类的doer函数。
预期输出:
Base::doer
Derived::doer
实际输出:
Base::doer
Base::doer
代码:
<?
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();
?>
这是相同的 C++ 代码示例,它可以工作:
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();
}
输出:
A::doit
B::doit
有趣的是,如果我更改我原来的 PHP 示例并将 private function 替换为 protected function 它开始工作:
<?
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();
?>
输出:
Base::doer
Derived::doer
有谁知道为什么 PHP 和 C++ 会产生不同的结果以及为什么在 PHP 中将 private 更改为 protected 会产生与 C++ 相同的结果?
【问题讨论】:
-
顺便说一句:除非您正在寻找麻烦,否则不要使用短标签
-
@MarcinOrlowski 什么是短标签?从来没有听说过。 (对不起!)
-
PHP 中的短标签意味着使用
<?而不是完整的<?php -
你能解释一下为什么短标签不好?
标签: php c++ oop inheritance private