1. 基礎
變數函數:
<?php $func = 'test'; function test(){ echo 'yes !'; } $func(); ?>
隨機函數:
<?php $newfunc = create_function('$a,$b', 'return $a.$b;'); echo "New anonymous function: $newfunc<br>"; echo $newfunc('just', 'coding'); ?>
create_function — Create an anonymous (lambda-style) function
函數。這個函數主要作用在unsort和array_walk的回調函數$a,$b為參數,'return $a,$b' 為函數的程式碼回呼函數:
<?php //5.3 以前 $array = array( 'asbc', 'ddd', 'tttt', 'qqq'); array_walk($array,create_function('&$item','$item=strtoupper($item);') ); //function(&$itm){$itm = strtoupper($itm);} print_r($array); //5.3 以后 $array = array( 'asbc', 'ddd', 'tttt', 'qqq'); array_walk($array,function(&$itm){$itm = strtoupper($itm);}); print_r($array); ?>
<?php /* create class */ class Record { /* record information will be held in here */ private $info; /* constructor */ function Record($record_array) { $record_array['body'] = 'this is a new attribution'; $this->info = $record_array; } /* dynamic function server */ function __call($method,$arguments) { $meth = $this->from_case(substr($method,3,strlen($method)-3)); return array_key_exists($meth,$this->info) ? $this->info[$meth] : false; } function from_case($str) { $str[0] = strtolower($str[0]); $func = create_function('$c', 'return "_" . strtolower($c[1]);'); // function ($c) { return "_" . strtolower($c[1]); } return preg_replace_callback('/([A-Z])/', $func, $str); } } /* usage */ $Record = new Record( array( 'id' => 12, 'title' => 'Greatest Hits', 'description' => 'The greatest hits from the best band in the world!' ) ); /* proof it works! */ echo 'The ID is: '.$Record->getId().'<br>'; // returns 12 echo 'The Title is: '.$Record->getTitle().'<br>'; // returns "Greatest Hits" echo 'The Description is: '.$Record->getDescription().'<br>'; //returns "The greatest hits from the best band in the world!" echo 'The Body is: '.$Record->getBody(); //returns "The greatest hits from the best band in the world!" ?>
...)array_walk() 函數對陣列中的每個元素套用回呼函數。如果成功則回傳 TRUE,否則回傳 FALSE。
典型情況下 function 接受兩個參數。 array 參數的值作為第一個,鍵名作為第二個。如果提供了可選參數 userdata ,將作為第三個參數傳遞給回呼函數。
2. 實例動態建立類別函數
rrreee