Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create loop templates in php

Tags:

c++

php

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 do the same in PHP?

like image 704
Sujit Agarwal Avatar asked May 28 '11 16:05

Sujit Agarwal


3 Answers

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.

like image 199
rjmunro Avatar answered Oct 31 '22 23:10

rjmunro


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]
like image 38
Tadeck Avatar answered Oct 31 '22 23:10

Tadeck


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);
}
like image 1
tamasd Avatar answered Oct 31 '22 21:10

tamasd