PHP菜鳥(3)PHP函數

來源:互聯網
上載者:User

標籤:php入門

  1. PHP自訂函數

    文法格式 function fun_name($var1,$var2...)

    {

    statements;

    }

    函數可以通過return 傳回值

    例如 

   function add($a, $b){   return a + b;   }

    函數的傳遞有三種方式:

    1.按值傳遞 形參的值不會影響到實參

    2.按引用傳遞 形參的值會影響到實參

   function add(&$a){   $a += 1;   }   $a = 1;   add($a);   echo $a; //$a=2

    3.預設參數

    又稱為選擇性參數,必須放在參數列表的最後,並且指定預設為空白

   function values($price, $tax=""){       $price = $price + $price * $tax;       echo "The price is $price";   }

     另外php函數可以通過return返回處理後的值 函數也可以嵌套使用

2.PHP的內建函數

     1.輸出函數

     int print(string args)

     echo arg1, arg2....

     int printf(string format, args...)  //直接通過printf向瀏覽器輸出

     string sprintf(string foramt, args...) //需要通過echo進一步輸出

    echo $name."<br>";    print $name."<br>";    printf("HI, my name is %s,my age is %d years old", $name, $age);    echo sprintf("HI, my name is %s,my age is %d years old", $name, $age);

     2.引用檔案函數

     作用,將一個源檔案中的程式碼封裝含到當前源檔案中使用。實現代碼重用。

     void include(string filename);//filename是檔案的路徑

     void require(string filename);

     void include_once(string filename);

     void require_once(string filename);

    <?php include("top.php");?>    <?php include("top.php");?>

     include與require的區別:

     當代嗎執行到include的時候,才會將外部檔案引用進來,然後讀取檔案的內容,引用發生錯誤,只會發生警告,代碼會繼續向下執行。

    代碼執行之前,PHP解譯器會將被引用檔案的內容替換require語句,組成一個新的PHP檔案,然後執行。一般將require語句放到檔案的起始位置,通常用來引用公用函數檔案和公用類檔案。


    include_once和require_once可以有效方式因檔案的重複引用而導致的函數重複定義。

    include_once在匯入檔案之前會檢查該檔案是否之前被匯入,如果被匯入了,不會匯入該檔案同時引發一個警告,但是不影響檔案繼續執行。

    require_once與include_once類似。如果被重複引用了會引發致命錯誤,程式不在執行。




======================================實戰=======================================

通過自訂函數防止新聞主題資訊出現中文亂碼

<?phpfunction chinesesubstr($str, $start, $length){    $strlen = $start + $len;    for($i=$start;$i<$strlen;$i++){        if(ord(substr($str,$i,1))>0xa0){            $tmpstr.=substr($str,$i,2);            $i++;            }else{            $tmpstr.=substr($str,$i,1);    {     return $tmpstr;}

     

本文出自 “厚積薄發” 部落格,請務必保留此出處http://joedlut.blog.51cto.com/6570198/1853654

PHP菜鳥(3)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.