在 PHP 中,如何将过程代码包装在类中?
我有一大块遗留的 php 代码,我需要与之交互,如下所示:
//legacy.php
function foo() {
}
function bar() {
}
我希望能够将这些遗留函数包装在一个类中或以某种方式 require_once ,而不污染该全局命名空间或更改原始文件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在类中使用 命名空间 或静态方法:
两者需要对文件进行轻微修改。例如,对于上面的示例(具有静态方法的类),对
bar()
的调用必须更改为Foo::bar()
。或者,使用命名空间:
在您的文件中:
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:
正如评论中提到的,我强烈建议将此视为重构练习的机会。
但假设您出于某种原因无法这样做,那么您问题的答案取决于原始legacy.php 文件中的函数是否在内部相互调用。
如果没有,那么是的,做这样的事情是相当简单的:
但请注意,这只会将它们设置为类中的公共函数,而不是静态的,因此为了调用它们,您必须实例化一个实例首先是类,可能是在代码的早期作为全局类(这将是单例类的典型示例)。
如果您使用的是 PHP5.3,您可能需要考虑使用 PHP命名空间 而不是一个类,这将解决必须实例化该类的问题。但其机制大致相同。
但是,如果您的函数在旧版 php 代码中相互调用,那么如果不至少对旧版代码进行一些编辑以将函数调用更改为新版本,则这一切都是不可能的。
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.