如何在PHP中创建循环模板 [英] How to create loop templates in php
本文介绍了如何在PHP中创建循环模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们可以在C ++中定义循环模板,缩短编码时间:
As we can define loop templates in C++, for making coding shorter:
#define fo(a,b,c) for( a = ( b ); a < ( c ); ++ a )
有什么办法在PHP中做同样的事情?
Is there any way to do the same in PHP?
推荐答案
免责声明:嗯,预处理器宏,但由于PHP的动态性质,不需要/使用预处理器。但是,您可以在其他函数中包装函数,例如下面的示例。
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.']';
});
上述代码在PHP 5.3中工作,并输出以下内容:
The above code works in PHP 5.3 and outputs the following:
[2][3][4][5][6][7][8][9]
这篇关于如何在PHP中创建循环模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文