首页  >  文章  >  php教程  >  PHP类中私有方法的内部引用

PHP类中私有方法的内部引用

WBOY
WBOY原创
2016-06-06 19:44:451191浏览

以前习惯了美工和前端开发,现在进阶后端,开始学习PHP,在学习类的时候,碰到了一个 私有 方法 调用的问题。 代码如下: 1 ? php 2 class Person { 3 public function say( $name , $age ) { 4 $con = $this -get( $name , $age ); // 这里的$this-是关键 5

以前习惯了美工和前端开发,现在进阶后端,开始学习PHP,在学习类的时候,碰到了一个私有方法调用的问题。

代码如下:

<span> 1</span> <span>php
</span><span> 2</span> <span>class</span><span> Person { 
</span><span> 3</span>     <span>public</span> <span>function</span> say(<span>$name</span>, <span>$age</span><span>) {  
</span><span> 4</span>         <span>$con</span> = <span>$this</span>->get(<span>$name</span>, <span>$age</span>); <span>//</span><span>这里的$this->是关键</span>
<span> 5</span>         <span>echo</span> "my name is :".<span>$name</span>."<br>"<span>;  
</span><span> 6</span>         <span>echo</span> "my age is :".<span>$age</span>."<br>"<span>;
</span><span> 7</span>         <span>echo</span> "get :".<span>$con</span>."<br>"<span>;        
</span><span> 8</span> <span>    }
</span><span> 9</span>     <span>private</span> <span>function</span> get(<span>$a</span>, <span>$b</span><span>) {
</span><span>10</span>         <span>$a</span> = <span>$a</span>.<span>$b</span><span>;
</span><span>11</span>         <span>return</span> <span>$a</span><span>;
</span><span>12</span> <span>    }
</span><span>13</span> 
<span>14</span> <span>}  
</span><span>15</span> 
<span>16</span> <span>$person</span>=<span>new</span><span> Person();  
</span><span>17</span> <span>$person</span>->say("ren", 25<span>);
</span><span>18</span> 
<span>19</span> ?>        

这段代码很简单,我想实现类的内部私有方法的调用。如第4行所示。以前写js习惯了,在调用get()方法时,没有在前面加上"$this",程序会出现问题。补上之后就可以调用了。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn