开发者

Does using a function in foreach loop caches the result, or calls the function each time?

In the following code:

function a(){
    echo 'a';
    return array(1,2,3,4);
}

foreach(a() as $t){
    echo $t;    
}

We can see a() is called only once, and it seems the returned v开发者_开发技巧alue is cached...

But then I got to see this debate (see comments on the question) am I missing something?


No, your test is conclusive.

It makes no sense for it to evaluate the first expression any more than once. It's the basic premise of a foreach loop.

A for loop has three arguments, and it does evaluate the second and third each iteration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜