1

I have a class that extends another class with unknown methods. Here is the base of the class:

class SomeClass extends SomeOtherClass {     
}

I also have an array that looks like this:

$array = array(
  'aFunctionName' => 'My Value',
  'anotherFunctionName' => 'My other value'
);

It contains the classname and a value. The question is how I can use them in the extended class, creating the classes on demand, dynamically.

Results

Here is the result of how the PHP should read the result of my array.

class SomeClass extends SomeOtherClass {

  public function aFunctionName() {
    return 'My value';
  }

  public function anotherFunctionName() {
    return 'My other value';
  }
}

Is it possible to create extended methods by an array like this?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

1 Answers1

4

You can use the __call to create magic methods, like this :

class Foo {

    private $methods;

    public function __construct(array $methods) {
        $this->methods = $methods;
    }

    public function __call($method, $arguments) {
        if(isset($this->methods[$method])) {
            return $this->methods[$method];
        }
    }
}

$array = array(
  'aFunctionName' => 'My Value',
  'anotherFunctionName' => 'My other value'
);

$foo = new Foo($array);
echo $foo->aFunctionName();
Guillaume Sainthillier
  • 1,655
  • 1
  • 9
  • 13