Heim >Backend-Entwicklung >PHP-Tutorial >PHP-Closure-Experiment

PHP-Closure-Experiment

巴扎黑
巴扎黑Original
2016-12-01 11:00:471068Durchsuche

class IArray extends ArrayObject  
{      
static function make($array)      
{          
return new self($array);      
}
function map($func)      
{          
$res = new self();
foreach ($this as $k => $v)   
{   
$res[$k] = $func($k, $v);          
}
return $res;      
}
function filter($func)      
{          
$res = new self();
foreach ($this as $k => $v)   
{              
if ($func($k, $v))   
{                  
$res[$k] = $v;             
}      
}
return $res;      
}
}
$nums = array(10,20,30,40);
$res = IArray::make($nums)->filter(function($k, $v) { return $v > 15; })->map(function($k, $v) { return $v * 2; });
print_r($res);

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn