PHP鍑芥暟鐨勫弬鏁


閫氳繃鍙傛暟鍒楄〃鍙互浼犻掍俊鎭埌鍑芥暟锛屽嵆浠ラ楀彿浣滀负鍒嗛殧绗︾殑琛ㄨ揪寮忓垪琛ㄣ

PHP 鏀寔鎸夊间紶閫掑弬鏁帮紙榛樿锛夛紝閫氳繃寮曠敤浼犻掑弬鏁颁互鍙婇粯璁ゅ弬鏁般備篃鏀寔鍙彉鏁伴噺鐨勫弬鏁帮紱鏇村淇℃伅璇峰弬鐓у彲鍙橀暱搴﹀弬鏁板垪琛ㄥ拰娑夊強鍒扮殑鐩稿叧鍑芥暟 func_num_args()锛宖unc_get_arg() 浠ュ強 func_get_args()銆


Example #1 鍚戝嚱鏁颁紶閫掓暟缁

<?php
function takes_array($input)
{
    echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
閫氳繃寮曠敤浼犻掑弬鏁
缂虹渷鎯呭喌涓嬶紝鍑芥暟鍙傛暟閫氳繃鍊间紶閫掞紙鍥犺屽嵆浣垮湪鍑芥暟鍐呴儴鏀瑰彉鍙傛暟鐨勫硷紝瀹冨苟涓嶄細鏀瑰彉鍑芥暟澶栭儴鐨勫硷級銆傚鏋滃笇鏈涘厑璁稿嚱鏁颁慨鏀瑰畠鐨勫弬鏁板硷紝蹇呴』閫氳繃寮曠敤浼犻掑弬鏁般

濡傛灉鎯宠鍑芥暟鐨勪竴涓弬鏁版绘槸閫氳繃寮曠敤浼犻掞紝鍙互鍦ㄥ嚱鏁板畾涔変腑璇ュ弬鏁扮殑鍓嶉潰棰勫厛鍔犱笂绗﹀彿 &锛


Example #2 鐢ㄥ紩鐢ㄤ紶閫掑嚱鏁板弬鏁

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>
榛樿鍙傛暟鐨勫
鍑芥暟鍙互瀹氫箟 C++ 椋庢牸鐨勬爣閲忓弬鏁伴粯璁ゅ硷紝濡備笅锛


Example #3 鍦ㄥ嚱鏁颁腑浣跨敤榛樿鍙傛暟

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type. ";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>
涓婇潰浠g爜娈电殑杈撳嚭鏄細


Making a cup of cappuccino.
Making a cup of .
Making a cup of espresso.

PHP 杩樺厑璁镐娇鐢ㄦ暟缁勫拰鐗规畩绫诲瀷 NULL 浣滀负榛樿鍙傛暟锛屼緥濡傦細


Example #4 浣跨敤闈炴爣閲忕被鍨嬩綔涓洪粯璁ゅ弬鏁

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
    $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
    return "Making a cup of ".join(", ", $types)." with $device. ";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>
榛樿鍊煎繀椤绘槸甯搁噺琛ㄨ揪寮忥紝涓嶈兘鏄濡傚彉閲忥紝绫绘垚鍛橈紝鎴栬呭嚱鏁拌皟鐢ㄧ瓑琛ㄨ揪寮忋

璇锋敞鎰忓綋浣跨敤榛樿鍙傛暟鏃讹紝浠讳綍榛樿鍙傛暟蹇呴』鏀惧湪浠讳綍闈為粯璁ゅ弬鏁扮殑鍙充晶锛涘惁鍒欙紝鍑芥暟灏嗕笉浼氭寜鐓ч鏈熺殑鎯呭喌宸ヤ綔銆傝冭檻涓嬮潰鐨勪唬鐮佺墖鏂細


Example #5 鍑芥暟榛樿鍙傛暟涓嶆纭殑鐢ㄦ硶

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
    return "Making a bowl of $type $flavour. ";
}

echo makeyogurt("raspberry");   // won't work as expected
?>
涓婅堪渚嬪瓙鐨勮緭鍑烘槸锛


Warning: Missing argument 2 in call to makeyogurt() in
/usr/local/etc/httpd/htdocs/php3test/functest.html on line 41
Making a bowl of raspberry .

鐜板湪锛屾瘮杈冧笂闈㈢殑渚嬪瓙鍜岃繖涓緥瀛愶細


Example #6 鍑芥暟榛樿鍙傛暟姝g‘鐨勭敤娉

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
    return "Making a bowl of $type $flavour. ";
}

echo makeyogurt("raspberry");   // works as expected
?>
杩欎釜渚嬪瓙鐨勮緭鍑烘槸锛


Making a bowl of acidophilus raspberry.

Note: 鑷 PHP 5 璧凤紝榛樿鍊煎彲浠ラ氳繃寮曠敤浼犻掋

鍙彉鏁伴噺鐨勫弬鏁板垪琛
PHP 4 鍙婃洿楂樼増鏈凡缁忓湪鐢ㄦ埛鑷畾涔夊嚱鏁颁腑鏀寔鍙彉鏁伴噺鐨勫弬鏁板垪琛ㄣ傚叾瀹炲緢绠鍗曪紝鍙渶浣跨敤 func_num_args()锛宖unc_get_arg()锛屽拰 func_get_args() 鍑芥暟鍗冲彲銆

鍙彉鍙傛暟骞朵笉闇瑕佺壒鍒殑璇硶锛屽弬鏁板垪琛ㄤ粛鎸夊嚱鏁板畾涔夌殑鏂瑰紡浼犻掔粰鍑芥暟锛屽苟鎸夐氬父鐨勬柟寮忎娇鐢ㄨ繖浜涘弬鏁般

浠ヤ笂灏辨槸PHP鍑芥暟鐨勫弬鏁扮殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



鏈枃URL锛http://www.odweb.cn/news_show.html?id=90