Home > Enterprise >  Methods to execute later in associative array as values
Methods to execute later in associative array as values

Time:11-13

I'm trying to build an associative array with values as methods to execute them after a filter process. To illustrate what I want to do, I have this classes:

class_one.php

<?php
  class ClassOne {

    public function __construct(){}
    
    public function task1($param1, $param2){
      echo "Performing task1 ..";
      $value = $param1   $param2;
      echo $value;
      return "{$value}";
    }

    public function task2($param1, $param2, $param3){
      echo "Performing task2 ..";
      return [$param1, $param2, $param3];
    }

    public function task3($param1){
      echo "Performing task3 ..";
      $result = [];
      for($i = 0; $i < 10; $i  ){
        $result[] = $param1 * $i;
      }
      return $result;
    }
  }
?>

class_two.php

<?php

  class ClassTwo {
    
    public function __construct(){}
    public function getValues(ClassOne &$class_one, array $filters){
      $func_map = [
        "task_1" => call_user_func_array(array($class_one, "task1"), array(1, 2)),
        "task_2" => call_user_func_array(array($class_one, "task2"), array(1, 2, 3)),
        "task_3" => call_user_func_array(array($class_one, "task3"), array(3))
      ];
      
      return array_intersect_key($func_map, array_flip($filters));
    }
  }
?>

index.php

<html>
  <head>
    <title>PHP Test</title>
  </head>
  <body>
    <?php 
    
    include("class_one.php");
    include("class_two.php");
    
    
    $class_one = new ClassOne();
    $class_two = new ClassTwo();

    $filters = ["task_1"];
    $func_map = $class_two->getValues($class_one, $filters);

    foreach($func_map as $key => $func){
      $func();
    }
    var_dump($func_map);
    
    ?> 
  </body>
</html>

Result expected:

Performing task1 ..
array(1) {
  ["task_1"]=>
  int(3)
}

However looks like all functions are executed during the assoc array assignment when calling getValues and seeing:

Performing task1 ..Performing task2 ..Performing task3 ..

CodePudding user response:

You're calling the functions when you create the associative array. You need to assign anonymous functions there.

And there's no need to use call_user_func_array(). Just call the methods normally.

      $func_map = [
        "task_1" => function() use ($class_one) { return $class_one->task1(1, 2); },
        "task_2" => function() use ($class_one) { return $class_one->task2(1, 2, 3); },
        "task_3" => function() use ($class_one) { return $class_one->task3(3); }
      ];
  •  Tags:  
  • php
  • Related