一个对象(或其他值)的内存只有在 PHP 进程中的任何地方都没有对它的引用时才能被释放。在您的情况下,该行$customer = null
仅将对该对象的引用数减少一,但不会使其达到零。
如果你考虑一个更简单的循环,这可能会变得更清楚:
$test = array('a' => 'hello');
foreach ( $test as $key => $value )
{
// $value points at the same memory location as $test['a']
// internally, that "zval" has a "refcount" of 2
$value = null;
// $value now points to a new memory location, but $test['a'] is unnaffected
// the refcount drops to 1, but no memory is freed
}
因为您使用的是对象,所以有一个额外的转折 - 您可以在循环内修改对象而无需创建它的新副本:
$test = array('a' => new __stdClass);
// $test['a'] is an empty object
foreach ( $test as $key => $value )
{
// $value points at the same object as $test['a']
// internally, that object has a "refcount" of 2
$value->foo = "Some data that wasn't there before";
// $value is still the same object as $test['a'], but that object now has extra data
// This requires additional memory to store that object
$value = null;
// $value now points to a new memory location, but $test['a'] is unnaffected
// the refcount drops to 1, but no memory is freed
}
// $test['a']->foo now contains the string assigned in the loop, consuming extra memory
在您的情况下,该->load()
方法可能会$customersCollection
依次扩展每个成员中的数据量,每个成员都需要更多内存。$customersCollection
在循环之前和之后检查可能会证实这一点。