PHP: 如何释放有限范围的变量?

PHP: How do I free limited scope variables?

我正在 "Fatal error: Allowed memory size of XXXX bytes exhausted..."。我需要遍历大量记录,并执行一个函数来验证记录是否符合声明许多 class 变量的条件。

foreach ($results as $row)
{
  $location = Location::parseDatabaseRow($row);

  if ($location->contains($lat, $lon))
  {
    $found = true;
    $locations[] = $location;
    break;
  }
}

实施地点class:

public function contains($lat, $lon)
{ 
  $polygon =& new polygon();
  .... //Add points to polygons base on location polygons
  $vertex =& new vertex($lat, $lon);
  $isContain = $polygon->isInside($vertex); 

  $polygon->res(); //Reset all variable inside polygons
  $polygon = null; //Let Garbage Collector clear it whenever
  return ($isContain);
}

contain() 方法是return 时$polygon 不应该清楚吗?我可以做些什么来减少内存使用量?

我是一名 Java 开发人员,并开始学习 PHP。请帮助我了解如何管理堆栈大小以及内存分配和分配。提前致谢。

I am a Java developer, and started to learn PHP.

这里有一些更正,可以让您的代码不会耗尽内存限制。

用一段时间。由于您的结果来自数据库查询,因此您应该可以使用 fetch() 而不是 fetchAll(),我假设您正在使用 foreach(),因为您正在对其应用 foreach()

while ($row = $result->fetch()) { // here $result is supposed to be a PDOStatatement.
    $location = Location::parseDatabaseRow($row);
    if ($location->contains($lat, $lon)) {
        $found = true; // where is this used?
        $locations[] = $location;
        break;
    }
}

虽然使用的内存较少,因为并非同时获取所有结果。

正确使用符号。你在每个循环中都在做一个新的。当你想通过引用传递一个值到一个函数时使用&符号,这样它就可以在函数范围之外受到影响而不需要return它。

在这里,您使用的对象在某种程度上是 passed by reference 设计的。

public function contains($lat, $lon) {
    $polygon = new polygon();
    $vertex = new vertex($lat, $lon);
    return $polygon->isInside($vertex);
    // no need to reset the values of your polygon, you will be creating a new one on the next loop.
}

为了完整起见,这里是使用相同多边形对象的版本。请注意我是如何不使用符号的,因为我们正在传递一个对象。

$polygon = new polygon();
while ($row = $result->fetch()) { // here $result is supposed to be a PDOStatatement.
    $location = Location::parseDatabaseRow($row);
    if ($location->contains($lat, $lon, $polygon)) {
        $found = true; // where is this used?
        $locations[] = $location;
        break;
    }
}

public function contains($lat, $lon, $polygon) {
    //Add points to the passed polygon
    $vertex = new vertex($lat, $lon);
    $isContain = $polygon->isInside($vertex);
    $polygon->res(); 
    // since we eill be using the same $polygon, now we need to reset it
    return $isContain;
}