开发者

PHP lambda functions and scope

开发者 https://www.devze.com 2023-02-19 01:29 出处:网络
The below function takes an array and checks to see if its keys and values match the specified datatypes.

The below function takes an array and checks to see if its keys and values match the specified datatypes.

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

  开发者_如何学JAVA  $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
)

Notice: Undefined variable: keytest in line 218

Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in line 218

Notice: Undefined variable: valtest in line 226

Warning: call_user_func() expects parameter 1 to be a valid callback, no array or string given in line 226

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) { ...


This is probably related to this bug: http://bugs.php.net/53958

Which has been fixed in 5.3.6

0

精彩评论

暂无评论...
验证码 换一张
取 消