首页  >  文章  >  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