php遞迴調用與靜態變數用法執行個體詳解

來源:互聯網
上載者:User
在PHP編程中,遞迴調用常常與靜態變數使用。靜態變數的含義可以參考PHP手冊.希望下面的代碼,會更有利於對遞迴以及靜態變數的理解

<?php //下面代碼會畫出一個很漂亮的葉子 // 定義 PI 一分的角度的值 define("PII", M_PI/180); // 建立映像資源,並定義其背景為 白色,前景色彩為 黑色 $im = imagecreate(670,500); $white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); $g = imagecolorallocate($im, 0x00, 0x00, 0x00); // 從下面執行個體化的代碼可以得知,初始值 $x, $y, $L, $a 別分為 300, 500, 100, 270 function drawLeaf($g, $x, $y, $L, $a) { global $im; $B = 50; $C = 9; $s1 = 2; $s2 = 3 ; $s3 = 1.2; if($L > $s1) { // 計算葉子的定位 上面 $x2 = $x + $L * cos($a * PII); $y2 = $y + $L * sin($a * PII); $x2R = $x2 + $L / $s2 * cos(($a + $B) * PII); $y2R = $y2 + $L / $s2 * sin(($a + $B) * PII); $x2L = $x2 + $L / $s2 * cos(($a - $B) * PII); $y2L = $y2 + $L / $s2 * sin(($a - $B) * PII); // 計算葉子的定位 下面 $x1 = $x + $L / $s2 * cos($a * PII); $y1 = $y + $L / $s2 * sin($a * PII); $x1L = $x1 + $L / $s2 * cos(($a - $B) * PII); $y1L = $y1 + $L / $s2 * sin(($a - $B) * PII); $x1R = $x1 + $L / $s2 * cos(($a + $B) * PII); $y1R = $y1 + $L / $s2 * sin(($a + $B) * PII); // 別分畫葉子的主幹以及葉面 ImageLine($im, (int)$x, (int)$y, (int)$x2, (int)$y2, $g); ImageLine($im, (int)$x2, (int)$y2, (int)$x2R, (int)$y2R, $g); ImageLine($im, (int)$x2, (int)$y2, (int)$x2L, (int)$y2L, $g); ImageLine($im, (int)$x1, (int)$y1, (int)$x1L, (int)$y1L, $g); ImageLine($im, (int)$x1, (int)$y1, (int)$x1R, (int)$y1R, $g); // 再次遞迴調用本身 drawLeaf($g, $x2, $y2, $L / $s3, $a + $C); drawLeaf($g, $x2R, $y2R, $L / $s2, $a + $B); drawLeaf($g, $x2L, $y2L, $L / $s2, $a - $B); drawLeaf($g, $x1L, $y1L, $L / $s2, $a - $B); drawLeaf($g, $x1R, $y1R, $L / $s2, $a + $B); } } // 執行個體化 drawLeaf($g, 300, 500, 100, 270); header("Content-type: image/png"); imagepng($im); ?>


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

header("Content-type: text/plain"); function static_function () { static $i = 0; if ($i++ < 10) { echo $i . "\n"; static_function(); } }

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.