php 不能重新定义类,重新定义类方法或类

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());

有点粗糙,但可以!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值