简体   繁体   English

我可以安全地在php foreach语句声明中放置一个函数吗?

[英]Can I safely put a function in php foreach statement declaration?

Is it safe to put a function in the foreach statement ? 在foreach语句中放置函数是否安全?

foreach( get_class_methods( $object ) as $entityMethod ) {
    // Do something
}

Does the get_class_methods() function will be called at each loop ? 是否在每个循环中调用get_class_methods()函数? Is there any drawback ? 有什么缺点吗?

The function will only get evaluated once, when entering the loop. 进入循环时,该函数只会被评估一次。 But you could have tested that yourself by making a function that increments a global variable every time it's called. 但是您可以通过创建一个在每次调用时递增全局变量的函数来测试自己。

As far as drawbacks, none that I can think of.. 至于弊端,我想不到的。

The only time this would be unsafe is if the function could return something that was not iterable (like null , or a string , etc). 唯一不安全的情况是函数是否可以返回不可迭代的内容(例如nullstring等)。 That particular function does return null on any error. 该特定函数的确会在发生任何错误时返回null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM