Php ArrayCollection::forAll带递归
今天,我在对带有递归的匿名函数使用ArrayCollection::forAll方法时发现了奇怪的行为 先决条件: 我有一个Php ArrayCollection::forAll带递归,php,symfony,recursion,doctrine,closures,Php,Symfony,Recursion,Doctrine,Closures,今天,我在对带有递归的匿名函数使用ArrayCollection::forAll方法时发现了奇怪的行为 先决条件: 我有一个Post实体的集合。每个Post都包含一组SocialPost实体 目标: 将所有Post和SocialPost实体的状态设置为“待定” 我的解决方案: 我想我可以使用非常简单的闭包,比如: $setPending = function($_, StatusAwareInterface $post) use (&$setPending) {
Post
实体的集合。每个Post
都包含一组SocialPost
实体
目标:
将所有Post和SocialPost实体的状态设置为“待定”
我的解决方案:
我想我可以使用非常简单的闭包,比如:
$setPending = function($_, StatusAwareInterface $post) use (&$setPending) {
echo "func entry point reached\r\n";
if ($post instanceof Post) {
echo "This is post. SP Count: " . count($post->getSocialPosts()) . "\r\n";
$post->getSocialPosts()->forAll($setPending);
$status = Post::STATUS_PENDING;
} else {
echo "This is SP\r\n";
$status = SocialPost::STATUS_PENDING;
}
$post->setStatus($status);
};
// $post contains 2 Post entities
// Each Post entity contains 50+ SocialPost entities
$posts->forAll($setPending);
结果:
但是输出非常奇怪。forAll似乎只使用第一项,然后中断:
func entry point reached
This is post. SP Count: 52
func entry point reached
This is SP
有人看到这个问题了吗?让我们检查一下
医生说:
* Applies the given predicate p to all elements of this collection,
* returning true, if the predicate yields true for all elements.
这可能是错误的,因为它没有说明,如果谓词返回false
,则整个函数forAll
立即返回false
。
让我们来看看来源:
public function forAll(Closure $p)
{
foreach ($this->elements as $key => $element) {
if ( ! $p($key, $element)) { // <-- here's null converted to false.
return false;
}
}
return true;
}
在匿名函数的和处
附加说明:对于所有
应理解为
检查集合中的每个元素是否与条件匹配
而不是
为集合的每个元素做一些事情
如果您想正确地执行此操作,只需执行
foreach
循环即可。是的,您是对的。我使用这种方法时假设它的工作原理与array_walk完全相同。非常感谢。
return true;