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?
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.
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]
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With