因为我不熟悉PHP,所以我将如何减少此处的代码重复?这两种方法在这里做的完全一样……除了提取字符串(filemtime和basename)并连接的部分.
private function modified_hash( $files ) {
$joined = "";
foreach ( $files as $file ) {
$joined .= filemtime( $file );
}
return $this->checksum( $joined );
}
private function filename_hash( $files ) {
$joined = "";
foreach ( $files as $file ) {
$joined .= basename( $file );
}
return $this->checksum( $joined );
}
解决方法:
代替两个函数,声明一个统一函数,并为关键的回调/函数名$func_name声明一个参数:
/**
* Gets joined files hash
*
* @param $files an array of file paths
* @param $func_name callback name
* @return mixed
*/
private function getFilesHash($files, callable $func_name) {
$joined = "";
foreach ($files as $file) {
$joined .= call_user_func($func_name, $file);
}
return $this->checksum($joined);
}
用法:
$fileHash = getFilesHash($files, 'basename');
使用的功能:
call_user_func