 Of course, many of us are familiar with this concept, but this article is designed for beginners. In this post I will try to consider this phenomenon and give examples of use. First you need to understand what is the lambda function. So, the lambda function, it is often called anonymous, that is, the function in the definition of which does not need to specify its name. The return value of such a function is assigned to a variable, through which this function can be called later.
 Of course, many of us are familiar with this concept, but this article is designed for beginners. In this post I will try to consider this phenomenon and give examples of use. First you need to understand what is the lambda function. So, the lambda function, it is often called anonymous, that is, the function in the definition of which does not need to specify its name. The return value of such a function is assigned to a variable, through which this function can be called later.<?php $temp = create_function( '$match', 'return (preg_match(\'/^{(.*)}$/\',$match[1],$m) ? "cms_$m[1]" : $match[1]);'); $query = 'SELECT * FROM {documents}'; $regExp = '/([^{"\']+|\'(?:\\\\\'.|[^\'])*\'|"(?:\\\\"|[^"])*"|{[^}{]+})/'; echo preg_replace_callback($regExp, $temp, $query); // SELECT * FROM cms_documents ?>  <?php class Builder { private $query; private $prefix; public function __construct($prefix='' ) { $this->query = $query; $this->prefix = $prefix; } public function replaceCallback( $match ) { return ( preg_match('/^{(.*)}$/',$match[1],$m) ? ( empty($this->prefix) ? $m[1] : "{$this->prefix}_$m[1]" ) : $match[1] ); } public function build($query) { static $regExp = '/([^{"\']+|\'(?:\\\\\'.|[^\'])*\'|"(?:\\\\"|[^"])*"|{[^}{]+})/'; return preg_replace_callback($regExp, array(&$this, "replaceCallback"), $query); } }; $builder = new Builder('cms'); echo $builder->build(“SELECT * FROM {documents}”); // SELECT * FROM cms_documents ?>  <?php $x = function( $number ) { return $number * 10; }; echo $x(8); //  80 ?>  <?php class ClosureTest { public $multiplier; public function __construct( $multilier ) { $this->multiplier = $multilier; } public function getClosure() { $mul = &$this->multiplier; return function( $number ) use( &$mul ) { return $mul * $number; }; } } $test = new ClosureTest(10); $x = $test->getClosure(); echo $x(8); //  80 $test->multiplier = 2; echo $x(8); //  16 ?>  <?php class QueryBuilder extends Builder { public function getQueryObject($query) { $self = $this; return function() use ($self,$query) { $argv = func_get_args(); foreach ( $argv as $i => $arg ) $argv[$i] = mysql_escape_string($arg); array_unshift($argv, $self->build($query)); return call_user_func_array( “sprintf”, $argv); }; } }; $builder = new QueryBuilder(); $deleteBook = $builder->getQueryObject(“DELETE FROM {documents} WHERE id=%d”); $deleteBook( $_GET['id'] ); ?> Source: https://habr.com/ru/post/121976/
All Articles