3 回答
![?](http://img1.sycdn.imooc.com/533e564d0001308602000200-100-100.jpg)
TA贡献1773条经验 获得超3个赞
runkit似乎是一个不错的解决方案,但默认情况下未启用它,并且其中的一部分仍处于试验阶段。因此,我一起砍掉了一个小类,该小类替换了类文件中的函数定义。用法示例:
class Patch {
private $_code;
public function __construct($include_file = null) {
if ( $include_file ) {
$this->includeCode($include_file);
}
}
public function setCode($code) {
$this->_code = $code;
}
public function includeCode($path) {
$fp = fopen($path,'r');
$contents = fread($fp, filesize($path));
$contents = str_replace('<?php','',$contents);
$contents = str_replace('?>','',$contents);
fclose($fp);
$this->setCode($contents);
}
function redefineFunction($new_function) {
preg_match('/function (.+)\(/', $new_function, $aryMatches);
$func_name = trim($aryMatches[1]);
if ( preg_match('/((private|protected|public) function '.$func_name.'[\w\W\n]+?)(private|protected|public)/s', $this->_code, $aryMatches) ) {
$search_code = $aryMatches[1];
$new_code = str_replace($search_code, $new_function."\n\n", $this->_code);
$this->setCode($new_code);
return true;
} else {
return false;
}
}
function getCode() {
return $this->_code;
}
}
然后包括要修改的类并重新定义其方法:
$objPatch = new Patch('path_to_class_file.php');
$objPatch->redefineFunction("
protected function foo(\$arg1, \$arg2)
{
return \$arg1+\$arg2;
}");
然后评估新代码:
eval($objPatch->getCode());
有点粗糙,但可以!
添加回答
举报