PHP學習之三:函數

來源:互聯網
上載者:User

1 建立函數

函數的建立文法如下:

function func($arg_1,$arg_2,...,$arg_n)

{

    ...

}

任何有效PHP代碼都可以在函數中,包含其他函數或類的定義。

在PHP中,調用函數時不需要先聲明。對於定義在函數中的函數,只有外層函數調用之後,才能調用內層函數。

<?phpfunction foo() {  function bar()   {    echo "I don't exist until foo() is called.\n";  }}/* We can't call bar() yet   since it doesn't exist. */foo();/* Now we can call bar(),   foo()'s processing has   made it accessible. */bar();?>

2 函數參數

PHP在傳遞參數時,支援按值傳遞(預設)、按引用傳遞。此外還支援預設參數與變長參數。

在按引用傳遞與預設參數時,其形式與C++一樣,如下代碼所示。

<?php/* passing by reference */function add_some_extra(&$string){    $string .= 'and something extra.';}/* passing default argument */function makecoffee($type = "cappuccino"){    return "Making a cup of $type.\n";}?>

需要注意的是,在傳遞預設參數時,必須是常量運算式,不能是變數、類成員函數或函數。此外,若有多個參數需要傳遞,預設參數必須位於非預設參數的右端。

在使用變長參數列表時,需要藉助於func_get_args() func_get_arg() , func_arg_num();

<?php// using varargs functionfunction pick($a) {    $argc = func_num_args();    for ($i = 0; $i < $argc; $i++) {        $arg = func_get_arg($i);        if (! is_null($arg)) {            return $arg;        }    }    return null;}?>

3 函數傳回值

函數可以返回任何類型的值,若無return語句,則返回NULL。

4 函數變數

PHP支援以字串的方式調用一個函數。下面的函數從一個類中執行這個操作。

<?phpclass Foo{    function Variable()    {        $name = 'Bar';        $this->$name(); // This calls the Bar() method    }        function Bar()    {        echo "This is Bar";    }}$foo = new Foo();$funcname = "Variable";$foo->$funcname();  // This calls $foo->Variable()?>

5 匿名函數

也稱為閉包。下面是一個使用了use引入外部參數的匿名函數。

<?phpfunction getTotal($tax,$products){        $total = 0.00;                $func =            function ($quantity, $product) use ($tax, &$total)            {                $pricePerItem = strtoupper($product));                $total += ($pricePerItem * $quantity) * ($tax + 1.0);            };                func(products);        return round($total, 2);    }?>
相關文章

聯繫我們

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