重新定义类方法或类

有没有不用典型继承就可以重新定义类或其某些方法的方法?例如:


class third_party_library {

    function buggy_function() {

        return 'bad result';

    }

    function other_functions(){

        return 'blah';

    }

}

我该怎么做才能代替buggy_function()?显然这是我想做的


class third_party_library redefines third_party_library{

    function buggy_function() {

        return 'good result';

    }

    function other_functions(){

        return 'blah';

    }

}

这是我的两难选择:我更新了破坏我的代码的第三方库。我不想直接修改该库,因为将来的更新可能会再次破坏代码。我正在寻找一种无缝的方法来替换类方法。


我发现这个库说可以做到,但是我很警惕,因为它已经有4年的历史了。


编辑:


我应该澄清的是,由于框架的限制,我不能将类从重命名为third_party_libraryto magical_third_party_library或其他任何名称。


就我的目的而言,是否可以向类中添加一个函数?我认为您可以在C#中使用“部分类”来完成此操作。


皈依舞
浏览 509回答 3
3回答

慕容3067478

runkit似乎是一个不错的解决方案,但默认情况下未启用它,并且其中的一部分仍处于试验阶段。因此,我一起砍掉了一个小类,该小类替换了类文件中的函数定义。用法示例:class Patch {private $_code;public function __construct($include_file = null) {&nbsp; &nbsp; if ( $include_file ) {&nbsp; &nbsp; &nbsp; &nbsp; $this->includeCode($include_file);&nbsp; &nbsp; }}public function setCode($code) {&nbsp; &nbsp; $this->_code = $code;}public function includeCode($path) {&nbsp; &nbsp; $fp = fopen($path,'r');&nbsp; &nbsp; $contents = fread($fp, filesize($path));&nbsp; &nbsp; $contents = str_replace('<?php','',$contents);&nbsp; &nbsp; $contents = str_replace('?>','',$contents);&nbsp; &nbsp; fclose($fp);&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $this->setCode($contents);}function redefineFunction($new_function) {&nbsp; &nbsp; preg_match('/function (.+)\(/', $new_function, $aryMatches);&nbsp; &nbsp; $func_name = trim($aryMatches[1]);&nbsp; &nbsp; if ( preg_match('/((private|protected|public) function '.$func_name.'[\w\W\n]+?)(private|protected|public)/s', $this->_code, $aryMatches) ) {&nbsp; &nbsp; &nbsp; &nbsp; $search_code = $aryMatches[1];&nbsp; &nbsp; &nbsp; &nbsp; $new_code = str_replace($search_code, $new_function."\n\n", $this->_code);&nbsp; &nbsp; &nbsp; &nbsp; $this->setCode($new_code);&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}function getCode() {&nbsp; &nbsp; return $this->_code;}}然后包括要修改的类并重新定义其方法:$objPatch = new Patch('path_to_class_file.php');$objPatch->redefineFunction("&nbsp; &nbsp; protected function foo(\$arg1, \$arg2)&nbsp; &nbsp; {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return \$arg1+\$arg2;&nbsp; &nbsp; }");然后评估新代码:eval($objPatch->getCode());有点粗糙,但可以!
打开App,查看更多内容
随时随地看视频慕课网APP