在PHP中,如何将过程代码包装在类中? [英] In PHP, how can I wrap procedural code in a class?
本文介绍了在PHP中,如何将过程代码包装在类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有大量的旧版php代码需要与之交互,如下所示:
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() {
}
我希望能够将这些遗留函数包装在一个类中或以某种方式require_once而不污染该全局名称空间或更改原始文件.
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:
// original file: foo.php
class Foo
{
public static function foo() { }
public static function bar() { }
}
// new file:
require 'foo.php';
class MyNewClass
{
public function myfunc()
{
Foo::foo();
}
}
$x = new MyNewClass();
$x->myfunc();
这两个文件都需要稍作修改.例如,在上述示例(具有静态方法的类)中,必须将对bar()
的调用更改为Foo::bar()
.
Both would require slight modifications to the file. e.g., Calls to bar()
would have to be changed to Foo::bar()
with the above example (class with static methods).
OR,使用命名空间:
OR, using a namespace:
namespace foo;
use \Exception;
// any other global classes
function foo() { }
function bar() { }
在您的文件中:
require 'foo.php';
foo\foo();
foo\bar();
这篇关于在PHP中,如何将过程代码包装在类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文