Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

php - 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);
        }
    }
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...