Search code examples
phpoopclassname

Include file with duplicate class


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.


Solution

  • 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.