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?

1

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.