PHP鐢ㄦ埛鑷畾涔夊嚱鏁


涓涓嚱鏁板彲鐢变互涓嬬殑璇硶鏉ュ畾涔夛紝Example #1 灞曠ず鍑芥暟鐢ㄩ旂殑浼唬鐮

涓涓嚱鏁板彲鐢变互涓嬬殑璇硶鏉ュ畾涔夛細

Example #1 灞曠ず鍑芥暟鐢ㄩ旂殑浼唬鐮

<?php
function foo($arg_1, $arg_2, ..., $arg_n)
{
    echo "Example function. ";
    return $retval;
}
?>
浠讳綍鏈夋晥鐨 PHP 浠g爜閮芥湁鍙兘鍑虹幇鍦ㄥ嚱鏁板唴閮紝鐢氳嚦鍖呮嫭鍏跺畠鍑芥暟鍜岀被瀹氫箟銆

鍑芥暟鍚嶅拰 PHP 涓殑鍏跺畠鏍囪瘑绗﹀懡鍚嶈鍒欑浉鍚屻傛湁鏁堢殑鍑芥暟鍚嶄互瀛楁瘝鎴栦笅鍒掔嚎鎵撳ご锛屽悗闈㈣窡瀛楁瘝锛屾暟瀛楁垨涓嬪垝绾裤傚彲浠ョ敤姝e垯琛ㄨ揪寮忚〃绀轰负锛歔a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*銆

Tip
璇峰弬瑙乁serland Naming Guide銆

闄ら潪鏄笅闈袱涓緥瀛愪腑鐨勬儏鍐碉紝鍑芥暟蹇呴』鍦ㄥ叾璋冪敤涔嬪墠瀹氫箟銆


Example #2 鏉′欢鍑芥暟(Conditional functions)

<?php

$makefoo = true;

/* 鎴戜滑涓嶈兘鍦ㄥ璋冪敤foo()鍑芥暟锛
   鍥犱负瀹冭繕涓嶅瓨鍦紝浣嗗彲浠ヨ皟鐢╞ar()鍑芥暟銆*/

bar();

if ($makefoo) {
  function foo()
  {
    echo "I don't exist until program execution reaches me. ";
  }
}

/* 鐜板湪鎴戜滑鍙互瀹夊叏璋冪敤鍑芥暟 foo()浜嗭紝
   鍥犱负 $makefoo 鍊间负鐪 */

if ($makefoo) foo();

function bar()
{
  echo "I exist immediately upon program start. ";
}

?>

Example #3 鍑芥暟涓殑鍑芥暟

<?php
function foo()
{
  function bar()
  {
    echo "I don't exist until foo() is called. ";
  }
}

/* 鐜板湪杩樹笉鑳借皟鐢╞ar()鍑芥暟锛屽洜涓哄畠杩樹笉瀛樺湪 */

foo();

/* 鐜板湪鍙互璋冪敤bar()鍑芥暟浜嗭紝鍥犱负foo()鍑芥暟
   鐨勬墽琛屼娇寰梑ar()鍑芥暟鍙樹负宸插畾涔夌殑鍑芥暟 */

bar();

?>
PHP 涓殑鎵鏈夊嚱鏁板拰绫婚兘鍏锋湁鍏ㄥ眬浣滅敤鍩燂紝鍙互鍦ㄥ唴閮ㄥ畾涔夊閮ㄨ皟鐢紝鍙嶄箣浜︾劧銆

PHP 涓嶆敮鎸佸嚱鏁伴噸杞斤紝涔熶笉鍙兘鍙栨秷瀹氫箟鎴栬呴噸瀹氫箟宸插0鏄庣殑鍑芥暟銆

Note: 鍑芥暟鍚嶆槸澶у皬鍐欐棤鍏崇殑锛屼笉杩囧湪璋冪敤鍑芥暟鐨勬椂鍊欙紝閫氬父浣跨敤鍏跺湪瀹氫箟鏃剁浉鍚岀殑褰㈠紡銆

PHP 鏀寔鍙彉鏁伴噺鐨勫弬鏁板拰榛樿鍙傛暟銆傚叿浣撹鍙傝冿細 func_num_args()锛宖unc_get_arg()锛屼互鍙奻unc_get_args()銆

鍦 PHP 涓彲浠ヨ皟鐢ㄩ掑綊鍑芥暟銆備絾鏄閬垮厤閫掑綊鍑芥暟锛忔柟娉曡皟鐢ㄨ秴杩 100-200 灞傦紝鍥犱负鍙兘浼氱牬鍧忓爢鏍堜粠鑰屼娇褰撳墠鑴氭湰缁堟銆

Example #4 閫掑綊鍑芥暟

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a ";
        recursion($a + 1);
    }
}
?>
 

浠ヤ笂灏辨槸PHP鐢ㄦ埛鑷畾涔夊嚱鏁扮殑璇︾粏鍐呭锛屾洿澶氫俊鎭鍏虫敞OD浜戝叾瀹冪浉鍏虫枃绔狅紒



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