Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 593
james Avatar asked Oct 24 '22 11:10

james


1 Answers

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();
like image 93
Matthew Avatar answered Oct 27 '22 09:10

Matthew