Home > Article > Backend Development > Dynamically create php class functions or functions
1. Basic
Variable function:
<?php $func = 'test'; function test(){ echo 'yes !'; } $func(); ?>
Random function:
<?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
Create an anonymous function. This function is mainly used in the callback functions of unsort and array_walk
$a, $b are parameters, 'return $a,$b' is the code of the function
Callback function:
<?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); ?>
array_walk(array, function, userdata ...)
array_walk() function applies a callback function to each element in the array. Returns TRUE if successful, FALSE otherwise.
Typically function accepts two parameters. The value of the array parameter is used as the first one, and the key name is used as the second one. If the optional parameter userdata is provided, it will be passed to the callback function as the third parameter.
2. Instance dynamic creation of class functions
<?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!" ?>
The key points are: __call and create_function