PHP Functions Creating Dynamic Functions - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Functions Creating Dynamic Functions - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Friday, May 24, 2019

PHP Functions Creating Dynamic Functions

PHP Functions



Creating Dynamic Functions

Problem

You want to create and define a function as your program is running.

Solution

Use the closure syntax to define a function and store it in a variable:

            $increment = 7;
            $add = function($i, $j) use ($increment) { return $i + $j + $increment; };

            $sum = $add(1, 2);

$sum is now 10. If you are using a version of PHP earlier than 5.3.0, use create_function() instead:

            $increment = 7;

            $add = create_function('$i,$j', 'return $i+$j + ' . $increment. ';');

            $sum = $add(1, 2);

Discussion

The closure syntax is much more pleasant than using create_function(). With create_function, the argument list and function body are written as literal strings. This means PHP can’t parse their syntax until runtime and you have to pay attention to single quoting and double quoting and variable interpolation rules.

With the closure syntax, PHP can do the same compile-time checking of your anonymous function as it does on the rest of your code.

You use the same syntax you’d use elsewhere for writing a function, with one exception: a use() declaration after the argument list can enumerate variables from the scope in which the closure is defined that should be available inside the closure. 

In the preceding example, the use($increment) means that, inside the closure, $increment has the value (7) that it does in the scope in which the closure is defined.

A frequent use for anonymous functions is to create custom sorting functions for usort() or array_walk():

            $files = array('ziggy.txt', '10steps.doc', '11pants.org', "frank.mov");
            // sort files in reverse natural order
            usort($files, function($a, $b) { return strnatcmp($b, $a); });
            // Now $files is
            // array('ziggy.txt', 'frank.mov','11pants.org','10steps.doc')



No comments:

Post a Comment

Post Top Ad