虽然PHP有<<<这种多行字符串的用法,但用着不爽啊,因为最后的结束行不能有空格。看看我写的这种字符串构造方法吧,代码如下:
/**把一个匿名函数的注释转换为字符串
* @param function $closure 匿名函数
* @param array $replace 替换占位字符的内容,占位字符的格式正则表现为{[0-9]+},比如{0}、{1} 其中数值对应$replace的索引
* @return string 返回匿名函数内的注释内容
*/
function string($closure,$replace=NULL){
$func = new ReflectionFunction($closure);
$start = $func->getStartLine() - 1;
$end = $func->getEndLine() - 1;
$filename = $func->getFileName();
$code=implode("", array_slice(file($filename),$start, $end - $start + 1));
$reg="/\\/\\*([^\\0]+)\\*\\//";
$match=array();
preg_match($reg,$code,$match);
if(count($match)>0){
if(!$replace){
return preg_replace("/\\\\\\\/","\\",preg_replace("/\*(\\\\\/)/", "*/", trim($match[1])));
}
if(count($replace)<=0){
return preg_replace("/\\\\\\\/","\\",preg_replace("/\*(\\\\\/)/", "*/", trim($match[1])));
}
$tmp1=$match[1];
for($i=0;$i<count($replace);$i++){
$r=$replace[$i];
$tmp1=str_replace("{".$i."}", $r, $tmp1);
}
return preg_replace('/\\\\\\\/','\\',preg_replace("/\*(\\\\\/)/", "*/", $tmp1));
}
return "";
}
$sql=string(function(){/*
select * from table1 T1
left join table2 T2 on T2.id=T1.id
where T1.id={0} && T2.name='{1}'
*/},array(101,"ioriliao"));
输出结果:
select * from table1 T1
left join table2 T2 on T2.id=T1.id
where T1.id=101 && T2.name='ioriliao'