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

女生的网名这么多〃 提交于 2019-12-23 12:57:16

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6060958/in-php-how-can-i-wrap-procedural-code-in-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!