1 <?php
 2      class Sum0 {
 3          public function sum() {
 4              return 0;
 5          }
 6      }
 7  
 8      class Test {
 9          private $a = array();
10  
11          public function __construct() {
12              $this->a[0] = new Sum0();
13              $this->a[1] = $this;
14          }
15  
16          public function sum($n) {
17              #这 !!n 是关键,当 n != 0 时, !!n = true = 1,进入递归,当 n == 0时,!!n = false = 0,递归中止,返回0
18              return $this->a[!!$n]->sum($n - 1) + $n;
19          }
20      }
21 
22      #第二种方法,网上抄的,屌爆了
23      #直接用&&来终止递归
24      function sumn($n) {
25          $r = 0;
26          $n && ($r = (sumn($n - 1) + $n));
27          return $r;
28      }
29  
30      $t = new Test();
31      echo $t->sum(5) . "<br>";
32      echo sumn(5);
33  ?>
posted on 2012-10-01 17:36  ZimZz  阅读(923)  评论(0编辑  收藏  举报