Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-06 19:45:42
Original
833 people have browsed it

在手册中遇到了一个没想明白的问题,记录一下: 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>
Copy after login

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

一些资料:

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

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

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

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template