Heim  >  Artikel  >  Backend-Entwicklung  >  PHP对象递归引用造成内存泄漏分析,php递归_PHP教程

PHP对象递归引用造成内存泄漏分析,php递归_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:19:55854Durchsuche

PHP对象递归引用造成内存泄漏分析,php递归

通常来说,如果PHP对象存在递归引用,就会出现内存泄漏。这个Bug在PHP里已经存在很久很久了,先让我们来重现这个Bug,示例代码如下:

<&#63;php
class Foo {
  function __construct() {
    $this->bar = new Bar($this);
  }
}

class Bar {
  function __construct($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < 100; $i++) {
  $obj = new Foo();

  unset($obj);
  echo memory_get_usage(), "/n";
}
&#63;> 

运行以上代码,你会发现,内存使用量本应该不变才对,可实际上却是不断增加,unset没有完全生效。

现在的开发很多都是基于框架进行的,应用里存在复杂的对象关系,那么就很可能会遇到这样的问题,下面看看有什么权宜之计:

<&#63;php
class Foo {
  function __construct() {
    $this->bar = new Bar($this);
  }

  function __destruct() {
    unset($this->bar);
  }
}

class Bar {
  function __construct($foo) {
    $this->foo = $foo;
  }
}

for ($i = 0; $i < 100; $i++) {
  $obj = new Foo();

  $obj->__destruct();
  unset($obj);
  echo memory_get_usage(), "/n";
}
&#63;>

办法有些丑陋,不过总算是对付过去了。幸运的是这个Bug在PHP5.3的CVS代码中已经被修复了

对此,在进行PHP程序设计时有必要加以注意!相信本文所述对大家的PHP程序设计有一定的参考价值。

PHP 递归的解释

函数demo有两个必然的输出语句,一个是开始的一个,一个是最后的一个!
函数运行流程
1.输出num
2.判断num大于0否从而确定是否调用函数
3.输出num

在num大于0时,每一次调用函数,都只执行到第2步,后等待第二步调用自身返回结果后继续执行,因此,每次调用自身结束返回后都重新输出一次num,也就是倒序输出了后面的数值!
 

php 递归调用

那好吧 随便啰嗦几句

写sql语句的时候 最好把mysql函数都大写 这样的话sql语句就一目了然 很好看的说。
比如:$sql = "SELECT * FROM `user` WHERE `id` = '$id'";

并且 表名 字段名都使用 ` 1旁边的点(英文输入法下的点)包含起来 并且给字段复制的变量 无论是字符串还是数字类型 都用' 单引号包含起来
可是很有好处的哦。。。。。
 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/871099.htmlTechArticlePHP对象递归引用造成内存泄漏分析,php递归 通常来说,如果PHP对象存在递归引用,就会出现内存泄漏。这个Bug在PHP里已经存在很久很久了,...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn