关于类继承的一个问题
Jun 06, 2016 pm 08:18 PM
下面的这段代码:
<code>class Bar { public function test () { $this -> testPrivate (); $this -> testPublic (); } public function testPublic () { echo "Bar::testPublic\n" ; } private function testPrivate () { echo "Bar::testPrivate\n" ; } } class Foo extends Bar { public function testPublic () { echo "Foo::testPublic\n" ; } private function testPrivate () { echo "Foo::testPrivate\n" ; } } $myFoo = new foo (); $myFoo -> test ();</code>
输出为什么是
<code>Bar::testPrivate Foo::testPubli</code>
而不是
<code>Foo::testPrivate Foo::testPubli</code>
回复内容:
下面的这段代码:
<code>class Bar { public function test () { $this -> testPrivate (); $this -> testPublic (); } public function testPublic () { echo "Bar::testPublic\n" ; } private function testPrivate () { echo "Bar::testPrivate\n" ; } } class Foo extends Bar { public function testPublic () { echo "Foo::testPublic\n" ; } private function testPrivate () { echo "Foo::testPrivate\n" ; } } $myFoo = new foo (); $myFoo -> test ();</code>
输出为什么是
<code>Bar::testPrivate Foo::testPubli</code>
而不是
<code>Foo::testPrivate Foo::testPubli</code>
Foo类里的testPublic()方法重写了父类Bar的testPublic();
而testPrivate()的属性是private,只能被同一个类对象访问,哪怕不是同一个实例,既然只能被同一个类对象访问,那肯定也不会被重写,所以才会出现上面的输出
私有方法不会被继承,所以由于test()
方法是在父类里面定义的,其中引用的私有方法始终都是调用父类的,不管子类里有没有定义与其同名的方法。
这个方法域有关,在调用Bar
的test
方法时,php
的calling scope
是Foo
,所以public
的方法会因为重写被覆盖掉,而private
的方法只会依照可见性采用Bar
里的方法。
父类中的private方法子类不能重写与调用
Foo 类虽然重写了两个方法,但是没有重写test()方法。
而执行父类的test方法时,$this是调用父类的私有方法,即父类有此私有方法,则调用父类的。父类没有,才会用子类的。

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Guide d'installation et de mise à niveau de PHP 8.4 pour Ubuntu et Debian

Comment configurer Visual Studio Code (VS Code) pour le développement PHP
