Php Dynamic class methods

84 Views Asked by At

I have an array (class property) which stores PHP methods (i.e., of class 'Closure'). Just like this.

$this->methods[$name]=$action;

$action is the function.

When I try invoking the function like $this->methods[$name](), I'm unable to access $this pointer inside function.

Why is this issue happening and how do I fix it.

2

There are 2 best solutions below

0
erwan On

You should have a look at "magic methods". http://php.net/manual/en/language.oop5.overloading.php#object.call

maybe you can try this implementation (not tested):

class MyClass
{
    public function __call($method_name, $arguments)
    {
        // $method_name is case sensitive
        $this->$method_name($arguments);
    }
   public function doSomethingCool($param){
      echo 'something cool happened';
   }
}

$obj = new MyClass();
$method = 'doSomethingCool';
$obj->$method('robert', 42)
4
Friedrich Roell On

I don't know if I understood your question. And if I did, I don't know why you would want to do this but:

<?php

class Foo
{
    protected $methods     = [];

    public    $some_number = 42;

    public function callFunction($action)
    {
        if ( ! array_key_exists($action, $this->methods)) {
            throw new Exception(sprintf('Method %s doesn\'t exist!', $action));
        }

        $this->methods[$action]($this);
    }

    public function addFunction(closure $closure, $label)
    {
        $this->methods[$label] = $closure;
    }
}

$foo = new Foo();

$foo->addFunction(function (Foo $context) {
    echo $context->some_number;
}, 'test');

$foo->callFunction('test');