doudong2149 2015-07-16 04:38
浏览 72
已采纳

包含具有重复类的文件

I want to include a file which contains a class that already exists in my application. Obviously this results in:

PHP Fatal error:  Cannot redeclare class XYZ

For reasons I won't go in to here, I cannot change the code of the file in question, nor the file which contains the original class. For this reason, I don't think that namespaces are an option - though I'm a bit new to the concept so I could be wrong.

  • Is there a way to dynamically change the contents of the file being read to change classname declaration on the fly?
  • Can I somehow destroy or un-include the duplicate class which already exists?

I realize this is not likely to be clean. Any ideas for a workaround no matter how ugly are welcome.

  • 写回答

1条回答 默认 最新

  • doulun5683 2015-07-16 05:32
    关注

    I'll answer my own question here per the idea mentioned in comments.

    $path = "/path/to/include/file.php";
    $className = "OriginalClassname";
    $tempClass = "ReplacementClassname";
    
    $buffer = file_get_contents($file);
    $buffer = str_replace($className,$tempClass,$buffer);
    $file = 'temp.php';
    file_put_contents($file, $buffer);
    include_once($file);
    unlink($file);
    

    In a nutshell:

    • read the file to a variable
    • replace the classname
    • write the variable to a temporary file
    • include temp file
    • remove temp file

    Worked like a charm.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探