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

I have a large snippet of old PHP code that I need to interact with, which looks like this:

//legacy.php function foo() { } function bar() { } 

I want to be able to wrap these deprecated functions in a class or require_once somehow, without polluting this global namespace or modifying the source file.

+4
source share
2 answers

You can use namespace or static methods in the 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 will require minor changes to the file. for example, bar() calls should be changed to Foo::bar() using 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
source

As mentioned in the comments, I would seriously recommend seeing this as an opportunity to refactor excersise.

But if you cannot do this for any reason, the answer to your question depends on whether the functions inside the legacy.php source file will be internal calls.

If not, then yes, it is pretty trivial to do something like this:

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

But note that this will simply install them as public functions inside the class, not static ones, so to call them you will first have to instantiate the class, perhaps at an early stage of your code, as global (this will be a classic example of a singleton class).

If you are using PHP5.3, you may need to use the PHP namespace rather than the class for this, which will solve the problem of instantiating the class. The mechanism would be the same though.

However, if your functions call each other in legacy php code, then none of these actions will be possible, at least for some changes in legacy code, to change function calls to their new versions.

+1
source

All Articles