How to create loop templates in php

后端 未结 4 1477
清酒与你
清酒与你 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:26

    CCPP seems to be closest thing available:

    #define macroFunction(op1,op2,op3) ((int)op1/((int)op2+(int)op3))
    #define hash_hash # ## #
    #define showCExamples 1
    
    #if showCExamples
    //Reference: http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation
    #define MYCASE(item,id) \
    case id: \
      item##_##id = id;\
    break
    
    switch(x) {
        MYCASE(widget,23);
    }
    
    0 讨论(0)
  • 2021-02-19 01:28

    How about something like:

    function my_macro($a, $b, $c) {
      $args = func_get_args();
      array_shift($args);
      array_shift($args);
      array_shift($args);
    
      return call_user_func_array("something_horrifically_long_involving_{$a}_{$b}_and_{$c}", $args);
    }
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2021-02-19 01:51

    Thankfully not. There are plenty of horrible things you can do to make unreadable PHP, but that isn't one of them.

    PHP doesn't use a preprocessor by default. Being a dynamic language, there isn't a build step for it to be run as part of. There are third party pre-processors you can use like CCPP, and of course you can write your own, but they are likely to change your workflows considerably.

    An interesting preprocessor for PHP was PiHiPi which tried to add useful features to the language like JSON like array syntax, rather than needing to write array() every time. Unfortunately, the author has pulled it.

    0 讨论(0)
提交回复
热议问题