1

我需要担心 PHP 的内存泄漏吗?特别是,我有以下从浏览器调用的代码。调用完成后,是否所有内容都已正确清理,或者我是否需要清除由创建的第一个数组创建的内存?

class SomeClass
{
  var $someArray = array();

  function someMethod()
  {
     $this->someArray[1] = "Some Value 1";
     $this->someArray[2] = "Some Value 2";
     $this->someArray[3] = "Some Value 3";
     $this->someArray = array();
     $this->someArray[1] = "Some other Value";
     $this->someArray[2] = "Some other Value";
     $this->someArray[3] = "Some other Value";
  }
}

someMethod();

谢谢,斯科特

4

3 回答 3

3

我需要担心 PHP 的内存泄漏吗?

It's possible to have a cyclic reference in PHP where the refcount of the zval never drops to 0. This will cause a memory leak (GC won't clean up objects that have a reference to them). This has been fixed in >= PHP 5.3.

In particular, I have the following code that is being called from a browser. When the call finishes, is everything cleaned up properly, or, do I need to clear the memory created by the first array that was created?

PHP scripts have a request lifecycle (run application, return response, close application), so it shouldn't be a worry. All memory used by your application should be marked as free'd when your application finishes, ready to be overwritten on the next request.

于 2012-06-22T01:13:02.487 回答
1

如果你是超级偏执狂,你总是可以unset的,但是,PHP 是一种垃圾收集语言,这意味着除非核心或扩展中存在错误,否则永远不会发生内存泄漏。

更多信息


附带说明一下,您应该使用较新的 PHP 5 OOP 语法。而且, someMethod 将是一个错误。它需要是 $obj->someMethod() 其中 $obj 是该类的一个实例。

于 2012-06-22T01:09:47.843 回答
1

There actually do exist memory problems if you run mod_php through Apache with the mpm_prefork behavior. The problem is that memory consumed by PHP is not released back to the operating system. The same Apache process can reuse the memory for subsequent requests, but it can't be used by other programs (not even other Apache processes).

One solution is to restart the processes from time to time, for example by setting the MaxRequestsPerChild setting to something rather low (100 or so, maybe lower for lightly loaded servers). The best solution is to not use mod_php at all but instead run PHP through FastCGI.

This is a sysadmin issue though, not a programmer issue.

于 2012-06-22T01:59:20.290 回答