动态类 php,动态创建php类函数或函数

1. 基础

变量函数:<?php

$func = 'test';

function test(){

echo 'yes !';

}

$func();

?>

随机函数:<?php

$newfunc = create_function('$a,$b', 'return $a.$b;');

echo "New anonymous function: $newfunc
";

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,

'title' => 'Greatest Hits',

'description' => 'The greatest hits from the best band in the world!'

)

);

/* proof it works! */

echo 'The ID is: '.$Record->getId().'
'; // returns 12

echo 'The Title is: '.$Record->getTitle().'
'; // returns "Greatest Hits"

echo 'The Description is: '.$Record->getDescription().'
'; //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

本条技术文章来源于互联网,如果无意侵犯您的权益请点击此处反馈版权投诉

本文系统来源:php中文网

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值