Execute methods listed in array

I have a class with attribute and methods similar to the code shown below, only more complex. The idea is to call an element in the dispatch array and then the methods listed for that element will be executed in the order they are listed. I am stuck on how to get the methods to execute (see Method called execute ()). Is it possible?

Note that setDispatch () is called in a constructor that is not shown in the code below.

// attribute
private $_dispatch = [];

// methods
public function execute()
{
  $dispatch = $this->getDispatch();
  // NEED LOGIC HERE THAT EXECUTES METHODS LISTED IN $dispatch['A']
}

private function setDispatch()
{
  $this->_dispatch = [
    'A' => [
        'method1',
        'method2',
        'method3'
    ],
    'B' => [
        'method4',
        'method3',
        'method1'
    ]
  ];
}
  
private function getDispatch()
{
  return $this->_dispatch;
}

private function method1()
{
  //do something
}

private function method2()
{
  //do something
}

private function method3()
{
  //do something
}

private function method4()
{
  //do something
}
      

Run codeHide result


+3


source to share


1 answer


I think you will like call_user_func and the php calling class function by string name

Keep in mind that call_user_func will not work as it does in your case and you need to use callback syntax , which means that the method name must be in an array with an object reference:[$object, $methodName]



// attribute
private $_dispatch = [];

// methods
public function execute()
{
  $dispatch = $this->getDispatch();
  foreach($dispatch['A'] as $methodName){
    call_user_func([$this, $methodName]);
  }
}

private function setDispatch()
{
  $this->_dispatch = [
    'A' => [
        'method1',
        'method2',
        'method3'
    ],
    'B' => [
        'method4',
        'method3',
        'method1'
    ]
  ];
}

private function getDispatch()
{
  return $this->_dispatch;
}

private function method1()
{
  //do something
}

private function method2()
{
  //do something
}

private function method3()
{
  //do something
}

private function method4()
{
  //do something
}

      

+6


source







All Articles