>  기사  >  php教程  >  PHP类与对象中的private访问控制的疑问

PHP类与对象中的private访问控制的疑问

WBOY
WBOY원래의
2016-06-06 19:45:42833검색

在手册中遇到了一个没想明白的问题,记录一下: 1 class Bar 2 { 3 public function test() { 4 $this - testPrivate(); 5 $this - testPublic(); 6 } 7 8 public function testPublic() { 9 echo "Bar::testPublic\n" ; 10 } 11 12 private function testPr

在手册中遇到了一个没想明白的问题,记录一下:

<span> 1</span> <span>class</span><span> Bar 
</span><span> 2</span> <span>{
</span><span> 3</span>     <span>public</span> <span>function</span><span> test() {
</span><span> 4</span>         <span>$this</span>-><span>testPrivate();
</span><span> 5</span>         <span>$this</span>-><span>testPublic();
</span><span> 6</span> <span>    }
</span><span> 7</span> 
<span> 8</span>     <span>public</span> <span>function</span><span> testPublic() {
</span><span> 9</span>         <span>echo</span> "Bar::testPublic\n"<span>;
</span><span>10</span> <span>    }
</span><span>11</span>     
<span>12</span>     <span>private</span> <span>function</span><span> testPrivate() {
</span><span>13</span>         <span>echo</span> "Bar::testPrivate\n"<span>;
</span><span>14</span> <span>    }
</span><span>15</span> <span>}
</span><span>16</span> 
<span>17</span> <span>class</span> Foo <span>extends</span><span> Bar 
</span><span>18</span> <span>{
</span><span>19</span>     <span>public</span> <span>function</span><span> testPublic() {
</span><span>20</span>         <span>echo</span> "Foo::testPublic\n"<span>;
</span><span>21</span> <span>    }
</span><span>22</span>     
<span>23</span>     <span>private</span> <span>function</span><span> testPrivate() {
</span><span>24</span>         <span>echo</span> "Foo::testPrivate\n"<span>;
</span><span>25</span> <span>    }
</span><span>26</span> <span>}
</span><span>27</span> 
<span>28</span> <span>$myFoo</span> = <span>new</span><span> foo();
</span><span>29</span> <span>$myFoo</span>->test(); <span>//</span><span> Bar::testPrivate 
</span><span>30</span> <span>                // Foo::testPublic</span>

为啥第一行会输出Bar::testPrivate呢?

一些资料:

http://www.haidx.com/php-private.html

还有php官网上,关于这段代码的贡献者回复中,也找到了一条:

http://www.php.net/manual/zh/language.oop5.visibility.php#87413

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.