php遞迴調用與靜態變數的使用

來源:互聯網
上載者:User
  1. //畫一個很漂亮的葉子
  2. // 定義 PI 一分的角度的值
  3. define("PII", M_PI/180);
  4. // 建立映像資源,並定義其背景為 白色,前景色彩為 黑色
  5. $im = imagecreate(670,500);
  6. $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
  7. $g = imagecolorallocate($im, 0x00, 0x00, 0x00);
  8. // 從下面執行個體化的代碼可以得知,初始值 $x, $y, $L, $a 別分為 300, 500, 100, 270
  9. function drawLeaf($g, $x, $y, $L, $a) {
  10. global $im;
  11. $B = 50;
  12. $C = 9;
  13. $s1 = 2;
  14. $s2 = 3 ;
  15. $s3 = 1.2;
  16. if($L > $s1) {
  17. // 計算葉子的定位 上面
  18. $x2 = $x + $L * cos($a * PII);
  19. $y2 = $y + $L * sin($a * PII);
  20. $x2R = $x2 + $L / $s2 * cos(($a + $B) * PII);
  21. $y2R = $y2 + $L / $s2 * sin(($a + $B) * PII);
  22. $x2L = $x2 + $L / $s2 * cos(($a - $B) * PII);
  23. $y2L = $y2 + $L / $s2 * sin(($a - $B) * PII);
  24. // 計算葉子的定位 下面
  25. $x1 = $x + $L / $s2 * cos($a * PII);
  26. $y1 = $y + $L / $s2 * sin($a * PII);
  27. $x1L = $x1 + $L / $s2 * cos(($a - $B) * PII);
  28. $y1L = $y1 + $L / $s2 * sin(($a - $B) * PII);
  29. $x1R = $x1 + $L / $s2 * cos(($a + $B) * PII);
  30. $y1R = $y1 + $L / $s2 * sin(($a + $B) * PII);
  31. // 別分畫葉子的主幹以及葉面
  32. ImageLine($im, (int)$x, (int)$y, (int)$x2, (int)$y2, $g);
  33. ImageLine($im, (int)$x2, (int)$y2, (int)$x2R, (int)$y2R, $g);
  34. ImageLine($im, (int)$x2, (int)$y2, (int)$x2L, (int)$y2L, $g);
  35. ImageLine($im, (int)$x1, (int)$y1, (int)$x1L, (int)$y1L, $g);
  36. ImageLine($im, (int)$x1, (int)$y1, (int)$x1R, (int)$y1R, $g);
  37. // 再次遞迴調用本身
  38. drawLeaf($g, $x2, $y2, $L / $s3, $a + $C);
  39. drawLeaf($g, $x2R, $y2R, $L / $s2, $a + $B);
  40. drawLeaf($g, $x2L, $y2L, $L / $s2, $a - $B);
  41. drawLeaf($g, $x1L, $y1L, $L / $s2, $a - $B);
  42. drawLeaf($g, $x1R, $y1R, $L / $s2, $a + $B);
  43. }
  44. }
  45. // 執行個體化
  46. drawLeaf($g, 300, 500, 100, 270);
  47. header("Content-type: image/png");
  48. imagepng($im);
  49. ?>
複製代碼

在php編程中,遞迴調用常常與靜態變數使用。靜態變數的含義可以參考 PHP 手冊。希望下面的代碼,會更有利於對遞迴以及靜態變數的理解

  1. header("Content-type: text/plain");
  2. function static_function () {
  3. static $i = 0;
  4. if ($i++ < 10) {
  5. echo $i . "\n";
  6. static_function();
  7. }
  8. }
  9. static_function();
複製代碼

以上代碼會如數輸出 1 到 10 的數字。在 static_function 函數第二次運行時,變數 i 由於是靜態變數,所以仍被保留不被釋放,進而可以得到自增的值。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.