In PHP, how can I wrap procedural code in a class?

2019-06-28 06:34发布

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.

2条回答
2楼-- · 2019-06-28 06:54

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();

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, using a namespace:

namespace foo;

use \Exception;
// any other global classes

function foo() { }
function bar() { }

In your file:

require 'foo.php';

foo\foo();
foo\bar();
查看更多
仙女界的扛把子
3楼-- · 2019-06-28 06:55

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:

<?php
class legacyFunctions {
require_once('legacy.php');
}
?>

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.

查看更多
登录 后发表回答