PHP lambda函数和作用域 [英] PHP lambda functions and scope
问题描述
以下函数接受一个数组,并检查其键和值是否与指定的数据类型匹配.
The below function takes an array and checks to see if its keys and values match the specified datatypes.
我似乎以前使用的内部lambda函数有一些问题.我正在运行PHP v5.3.6.他们上一次在v5.3.4下工作.他们抱怨未传递的变量不在范围内.如果我将该变量重新声明为global
,则错误消失了,但是变量为空.
I seem to be having some problems with the internal lambda functions that were previously working. I'm running PHP v5.3.6. They last worked under v5.3.4. They are complaining that the non-passed variable is not in scope. If I restate that variable as global
then the error goes away, but the variable is empty.
/**
* @param array $arr, array to be tested
* @param mixed $keytype
* @param mixed $valuetype
* @example acceptable_arr( array(1,2,3,4,'string'), NULL, 'integer') returns false
* @example acceptable_arr( array('thing'=>1,'other'=>2), 'string', 'integer') returns true
* @example acceptable_arr( array('thing'=>1,'other'=>2), 'string', 'array') returns false
*/
function acceptable_arr(array $arr,$keytype=NULL,$valuetype=NULL){
print_r(func_get_args()); //debugging
$valfail=true; $keyfail=true;
if($keytype==NULL && $valuetype==NULL) return true;
if(!is_null($keytype)) {
$keytest='is_'.$keytype;
if(function_exists($keytest)){
$fn_kfail=function($v){return call_user_func($keytest,$v);}; //PROBLEM LINE 218
$keyfail=(!is_null($keytype)) ? array_sum(array_map($fn_kfail,array_keys($arr))) : false;
}
}
if(!is_null($valuetype)) {
$valtest='is_'.$valuetype;
if(function_exists($valtest)){
$fn_vfail=function($v){return call_user_func($valtest,$v);}; //PROBLEM LINE 226
$valfail=(!is_null($valuetype)) ? array_sum(array_map($fn_vfail,$arr)) : false;
}
}
return !($valfail && $keyfail);
}
运行上面的函数将输出以下内容:
Running the above function outputs this:
Array
(
[0] => Array
(
[0] => main
)
[1] => integer
[2] => string
)
注意:未定义变量:keytest输入 218行
Notice: Undefined variable: keytest in line 218
警告:call_user_func()预期 参数1是有效的回调,否 第218行中给出的数组或字符串
Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in line 218
注意:未定义的变量:valtest in 226行
Notice: Undefined variable: valtest in line 226
警告:call_user_func()预期 参数1是有效的回调,否 在第226行中给出的数组或字符串
Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in line 226
$ keytest和$ valtest值去哪里了?为什么即使我这样声明它们都是全局的,它们在lambda函数中也为空?
Where did the $keytest and $valtest values go? Why are they empty inside the lambda functions even if I declare them global like this?
$fn_vfail=function($v){
global $valtest;
return call_user_func($valtest,$v);
};
推荐答案
function($v) use ($valtest) { ...
这篇关于PHP lambda函数和作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!