I have a large chunk of legacy php code that I need to interface with that looks like this:
//legacy.php
function foo() {
}
function bar() {
}
I want to be able to wrap these legacy functions in a class or somehow require_once without polluting that global namespace or altering the original file.
You can use a namespace or static methods in a class:
Both would require slight modifications to the file. e.g., Calls to
bar()
would have to be changed toFoo::bar()
with the above example (class with static methods).OR, using a namespace:
In your file:
As mentioned in the comments, I'd seriously recommend seeing this as an opportunity for a refactoring excersise.
But assuming you can't do that for whatever reason, the answer to your question depends on whether the functions within the original legacy.php file call each other internally.
If not, then yes, it's fairly trivial to do something like this:
But note that this will just set them up as public functions within the class, rather than static, so in order to call them, you would have to instantiate an instance of the class first, possibly early on in your code as a global (it would be a classic example of a singleton class).
If you're using PHP5.3, you might want to consider using a PHP namespace rather than a class for this, which would resolve the issue of having to instantiate the class. The mechanism would be much the same though.
However, if your functions call each other within the legacy php code, then none of this will be possible without at least some edits to your legacy code to change the function calls to their new versions.