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); }?>