How to create loop templates in php

后端 未结 4 1498
清酒与你
清酒与你 2021-02-19 00:56

As we can define loop templates in C++, for making coding shorter:

#define fo(a,b,c) for( a = ( b ); a < ( c ); ++ a )

Is there any way to d

4条回答
  •  忘掉有多难
    2021-02-19 01:35

    Disclaimer: Well, this is not exactly preprocessor macro, but due to "dynamic" nature of PHP, preprocessors are not needed/used. Instead however, you are able to wrap functions in other functions, like in the example below.

    Yes, you can do this by creating your own function that is being passed also a callback. Here is the example:

    // FO function
    function fo($b, $c, $callback) {
        for ($a = $b; $a < $c; ++$a) {
            $callback($a);
        }
    }
    
    // example of usage
    fo(2,10, function($a){
        echo '['.$a.']';
    });
    

    The above code works in PHP 5.3 and outputs the following:

    [2][3][4][5][6][7][8][9]
    

提交回复
热议问题