为何PHP中不可通过base调用派生类函数?
我写了这个简单的例子来说明我的问题.我有一个Base类和Derived类.当我调用派生类的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++产生不同的结果?为什么改变private
以protected
在PHP使它产生相同的结果为C++?
1> schtever..:
请参阅public,private和protected之间的区别是什么?有关PHP中的public,protected和private的讨论.
这是我的看法:
该函数justdoit
在Base
类中声明.当doer
被声明private
在Derived
类,它具有外部不可见Derived
类,甚至没有给Base
类.因此,即使justdoit
在实例上Derived
执行,它也会执行doer
in,Base
因为这是唯一doer
可见的函数.
PHP之友评论