Rumah >pembangunan bahagian belakang >tutorial php >PHP类中私有方法的内部引用,php类私有引用_PHP教程
以前习惯了美工和前端开发,现在进阶后端,开始学习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",程序会出现问题。补上之后就可以调用了。