• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

动态创建php 类函数或函数

php 搞代码 3年前 (2022-01-22) 20次浏览 已收录 0个评论

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);  ?>

array_walk(array,function,userdata…)

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

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

2. 实例动态创建类函数

<?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,  <i style="color:transparent">@本文来源gaodai$ma#com搞$代*码6网</i><b>搞代gaodaima码</b>        '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!"  ?>

重点在于: __call 和 create_function


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:动态创建php 类函数或函数

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址