PHP中遞迴的實現(附例子)

來源:互聯網
上載者:User

標籤:引用   function   span   return   遞迴   test   調用   adl   變數   

遞迴函式是一種調用自己的函數。寫遞迴函式時要小心,因為可能會無窮遞迴下去。必須確保有充分的方法來終止遞迴。

一:使用參數引用完成遞迴函式。操作的是同一塊記憶體位址。

<?php
$i=1;
function test(&$i)
{
    echo $i;
    $i++;
    if ($i <10)
    {
        test($i);
    }
}
test($i);//輸出123456789

test($i);//輸出10

?>

二:使用全域變數完成遞迴函式。在函數域內部用 global 語句匯入的一個真正的全域變數實際上是建立了一個到全域變數的引用。例子中,test()函數內部的 $i 實際上只是程式第一行中($i = 1;)的變數 $i 的一個應用;

<?php
$i = 1;
function test()
{
    global$i;
    echo $i;
    $i++;
    if ($i <10)
    {
        test();
    }
}
test();//輸出123456789

test();//輸出10

?>

 

三:使用靜態變數完成遞迴函式。static的作用:僅在第一次調用函數的時候對變數進行初始化,並且保留變數值。

<?php
function test()
{
    static $i 1;
    echo $i;

    $i++;
    if ($i < 10) {
        test();
    }
    $i--;//在每一層遞迴結束時自減,這一句可以協助理解遞迴函式的執行過程
}

test();//輸出123456789

test();//輸出123456789
?>

 
例1. 使用全域變數的情況遞迴遍曆檔案夾下的所有檔案

function getFiles($dir)

{

    global $arr;

    if(is_dir($dir)){

        $hadle =@opendir($dir);

       while($file=readdir($hadle) )

        {

           if(!in_array($file,array(‘.‘, ‘..‘)) )

            {

                $dirr= $dir.‘/‘.$file;

               if(is_dir($dirr))

                {

                   getFiles($dirr);

               }else{

                   array_push($arr, $dirr);

                }

            }

        }

    }

}

$arr = array();

getFiles(‘E:/logs‘);

print_r($arr);  

  

例2:使用靜態變數的情況遞迴遍曆檔案夾下的所有檔案

function getFiles ($dir)

{

    static $arr = array();

    if(is_dir($dir)){

        $hadle = opendir($dir);

        while($file=readdir($hadle))

        {

            if(!in_array($file,array(‘.‘,‘..‘)))

            {

                $dirr =$dir."/".$file;

                if(is_dir($dirr))

                {

                    getFiles ($dirr);

                }else{

                   array_push($arr,$dirr);

                }

               

            }

        }

    }

    return $arr;

}

 

$rows= array();

$rows = getFiles (‘E:/logs‘);

print_r($rows);

PHP中遞迴的實現(附例子)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.