Skip to content
Advertisement

Is it good pratice to add closure inside constructor?

I have added closure inside the constructor and unsure of its performance as well as best practice. What is the best way to do that if it is not the right way to do it?

<?php


class Foo
{
    private $operation;

    public function __construct(){
        $this->operation = [
            "==" => function($a,$b) {return $a == $b;}
        ];
    }
    public function processComparision($operand1,$operator,$operand2){
        if($operator == "=="){
            $func = $this->operation[$operator];
            return $func($operand1,$operand2);
        }
    }
}
?>

Advertisement

Answer

I have an own array class with a lot of functions (or closures) defined in the constructor. This type of definition of functions also allows you to add your own functions with a method.

  public function addSqlFunction($name, $function){
    $this->userFct[$name] = $function;
    return $this;
  }

I only see advantages in doing this. I’m also happy with the speed. It is therefore “best practice” for me.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement