Hello, dear reader. In this article, I would like to tell you about one feature described in the documentation, but not particularly used or not found its place in the modern PHP world.
Declaration of functions within other functions
Suppose you decide to define one function that will register other functions.
This behavior is not quite typical, but it may have its own advantages and methods of application.
function init() { function finish($resource) {
Declare functions inside methods
You determine the class, methods, body of methods, and at one point you, reading
stackoverflow or
reddit , and trying to run
it on 3v4l.org , realize that the possibility that the PHP interpreter provides is, on the one hand, very controversial, and on the other makes it possible to define any functionality only on request.
')
class test { function register() { if (!function_exists('test_init')) { function test_init() { echo 'Initializing library'.PHP_EOL; } } } } $test = new test; $test->register(); test_init();
This code is successfully executed on
PHP 4.x (> = 4.3.10), PHP 5 (> = 5.0.5), PHP 7, and HHVM .
Apparently, someone needed such functionality, and in 2005, a
bug was created describing this functionality.
PS:
In 2015, it is not at all necessary to use global functions, and even more so to define nested ones, but this opportunity is alive and most likely will not be removed from the language soon.