/***************************by garcon1986********************************/ <?php //example1 $makefoo = true; bar(); if($makefoo){ function foo(){ echo "doesn't exist.<br>"; } } if($makefoo)foo(); function bar(){ echo "exist<br>"; } //example2 function sjg(){ function wl(){ echo 'must call sjg() before wl()!<br>'; } } sjg(); wl(); //wl(); //sjg(); //example3 - 递归 $a = 10; function recursion($a){ if($a <= 20){ echo "$a/n"; recursion($a+1); } } recursion($a); echo "<br>"; //example4 - 向函数传递数组 $input1=array('hi','ni','hao','ya'); function record($input1){ echo $input1[0],$input1[1],$input1[2]; } record($input1); //pass the function's parameter by reference function add_some_extra(&$string){ $string .= 'wl wo ai ni.'; } $str1 = 'wo xiang shuo,'; add_some_extra($str1); echo $str1.'<br>'; //output: wo xiang shuo, wl wo ai ni. //default parameter 默认参数 function makecoffee($category = "cappuccino"){ //return "makeing a cup of $category./n"; echo "making a cup of $category"; } echo makecoffee().'<br>'; echo makecoffee("espresso").'<br>'; // add one more parameter function makeyogurt($type = "acidophilus", $flavour) { return "making a bowl of $type and $flavour/n".'<br>'; //return "Makin a bowl of $flavour/n"; } echo makeyogurt("","raspberry"); // won't work as expected //echo makeyogurt(); function makeyogurt2($flavour,$type = "acidophilus") { //return "making a bowl of $type and $flavour/n".'<br>'; return "Makin a bowl of $flavour $type/n"; } echo makeyogurt2("raspberry").'<br>'; // will work as expected //return 示例 function square($num){ return $num * $num; } echo square(4).'<p>'; function small_numbers(){ return array(0,1,2); } list($zero,$one,$two) = small_numbers(); echo $zero,$one,$two.'<p>'; function &returns_reference(){ return $someref; } $newref = & returns_reference(); echo $newref; //变量函数 function foo2(){ echo "in foo2() <br>/n"; } function bar2($args=''){ echo "in bar2(); argument was '$args'.<br />/n"; } function echoit($string){ echo $string.'<br>'; } function lm(){ echo "wxryy.<br>"; } $func = 'foo2'; $func(); $func = 'bar2'; $func('test'); $func = 'echoit'; $func('test'); $funct = 'lm'; $funct('wl'); // variable method class Foo{ function Variable(){ $name = 'Bar3'; $this->$name(); // this calls to Bar3 } function Bar3() { echo "This is Bar3"; } } $foo = new Foo(); $functname = "Variable"; $foo->$functname(); // this calls $foo->Variable() ?>