当前位置:Gxlcms > PHP教程 > 动态创建php类函数或函数

动态创建php类函数或函数

时间:2021-07-01 10:21:17 帮助过:14人阅读

1. 基础

变量函数:

  1. <?php
  2. $func = 'test';
  3. function test(){
  4. echo 'yes !';
  5. }
  6. $func();
  7. ?>

随机函数:

  1. <?php
  2. $newfunc = create_function('$a,$b', 'return $a.$b;');
  3. echo "New anonymous function: $newfunc<br>";
  4. echo $newfunc('just', 'coding');
  5. ?>

create_function — Create an anonymous (lambda-style) function

创建一个匿名函数。这个函数主要作用在unsort和array_walk的回调函数

$a,$b为参数,'return $a,$b' 为函数的代码

回调函数 :

  1. <?php
  2. //5.3 以前
  3. $array = array( 'asbc', 'ddd', 'tttt', 'qqq');
  4. array_walk($array,create_function('&$item','$item=strtoupper($item);') ); //function(&$itm){$itm = strtoupper($itm);}
  5. print_r($array);
  6. //5.3 以后
  7. $array = array( 'asbc', 'ddd', 'tttt', 'qqq');
  8. array_walk($array,function(&$itm){$itm = strtoupper($itm);});
  9. print_r($array);
  10. ?>

array_walk(array,function,userdata...)

array_walk() 函数对数组中的每个元素应用回调函数。如果成功则返回 TRUE,否则返回 FALSE。

典型情况下 function 接受两个参数。array 参数的值作为第一个,键名作为第二个。如果提供了可选参数 userdata ,将被作为第三个参数传递给回调函数。

2. 实例动态创建类函数

  1. <?php
  2. /* create class */
  3. class Record {
  4. /* record information will be held in here */
  5. private $info;
  6. /* constructor */
  7. function Record($record_array) {
  8. $record_array['body'] = 'this is a new attribution';
  9. $this->info = $record_array;
  10. }
  11. /* dynamic function server */
  12. function __call($method,$arguments) {
  13. $meth = $this->from_case(substr($method,3,strlen($method)-3));
  14. return array_key_exists($meth,$this->info) ? $this->info[$meth] : false;
  15. }
  16. function from_case($str) {
  17. $str[0] = strtolower($str[0]);
  18. $func = create_function('$c', 'return "_" . strtolower($c[1]);'); // function ($c) { return "_" . strtolower($c[1]); }
  19. return preg_replace_callback('/([A-Z])/', $func, $str);
  20. }
  21. }
  22. /* usage */
  23. $Record = new Record(
  24. array(
  25. 'id' => 12,
  26. 'title' => 'Greatest Hits',
  27. 'description' => 'The greatest hits from the best band in the world!'
  28. )
  29. );
  30. /* proof it works! */
  31. echo 'The ID is: '.$Record->getId().'<br>'; // returns 12
  32. echo 'The Title is: '.$Record->getTitle().'<br>'; // returns "Greatest Hits"
  33. echo 'The Description is: '.$Record->getDescription().'<br>'; //returns "The greatest hits from the best band in the world!"
  34. echo 'The Body is: '.$Record->getBody(); //returns "The greatest hits from the best band in the world!"
  35. ?>

重点在于: __call 和 create_function

人气教程排行