【问题标题】:destroy object in php在php中销毁对象
【发布时间】:2011-05-12 01:09:20
【问题描述】:

我在 PHP 中执行一个程序,有时会出现以下错误。这是由于创建了很多对象而没有破坏它们还是任何其他原因?

允许的内存大小为 16777216 字节已用尽(尝试分配 19456 字节) 在 PHP5 中销毁对象的正确方法是什么。

一些代码:

App::import('Vendor','GoogleShipping',array('file'=>'googlecheckout'.DS.'library'.DS.'googleshipping.php'));
App::import('Vendor','GoogleTax',array('file'=>'googlecheckout'.DS.'library'.DS.'googletax.php'));
class Cart{
    var $_itemname;
    var $_unit_price;
    public function Usecase($itemname,$unit_price,$url,$merchant_private_item_data)
    {
            $cart = new GoogleCart($this->_merchant_id, $this->_merchant_key, $this->_server_type,$this->_currency);
            $item_1 = new GoogleItem($this->_itemname,$this->_item_description,$this->_total_count,$this->_unit_price,$this->_merchant_private_item_data);
    }
}

【问题讨论】:

  • App::import('Vendor','GoogleShipping' ,array('file'=>'googlecheckout'.DS.'library'.DS.'googleshipping.php')); App::import('Vendor','GoogleTax' ,array('file'=>'googlecheckout'.DS.'library'.DS.'googletax.php'));类购物车{ var $_itemname;变量 $_unit_price;
  • 公共函数用例($itemname,$unit_price,$url,$merchant_private_item_data) { $cart = new GoogleCart($this->_merchant_id, $this->_merchant_key, $this->_server_type,$ this->_currency); $item_1 = new GoogleItem($this->_itemname,$this->_item_description,$this->_total_count,$this->_unit_price,$this->_merchant_private_item_data);}
  • 我导入的每个类也会创建一些对象
  • 您可以使用编辑按钮 (stackoverflow.com/posts/4215324/edit) 编辑您的帖子,然后请将代码块中的代码附加到您的帖子中

标签: php object memory garbage-collection


【解决方案1】:

由于我在很多地方使用大量的 APP::import 来在 cakephp 中导入供应商文件,它会消耗更多的内存。

我没有使用 APP::import,而是使用了 require_once() 并且没有发生错误。

【讨论】:

    【解决方案2】:

    使用unset 销毁对对象的引用。当所有引用都消失时,对象将被销毁。

    您还可以使用memory_get_usage 函数查看您目前使用的内存量。尝试使用它找出您的内存瓶颈在哪里。

    【讨论】:

      【解决方案3】:

      如果你这样做了,例如:

      for($i=0;$i<=10000;$i++)
      {
          $Object = new MyObject();
          //Blah
          unset($Object);
      }
      

      您不仅创建对象 10K 次,还使用 ​​unset 10K 次,这会降低应用程序的速度

      如果像这样迭代,你最好让它们超过 X 数量:

      $array = array();
      $count = 0;
      for($i=0;$i<=10000;$i++)
      {
          $array[$i] = new MyObject();
          //Blah
          $i++;
          if($count == 500)
          {
              unset($array,$count);
              $array = $array();
              $count = 0;
          }
      }
      

      现在你的记忆力应该不会达到峰值,而且你只使用 unset 20 次 :)

      这样你的储蓄性能也是如此。

      【讨论】:

      • 你错过了$count的增量
      【解决方案4】:

      没有看到代码,我们无法确切地知道是什么导致了这个错误。它可能会创建太多对象,但也可能很容易创建太大的数组或其他数据。

      无论您创建什么类型的数据引发错误,无论哪种方式,都可能是循环或递归函数失控,这是根本原因,在每次迭代时创建新数据,而不是您故意创建足够多的对象来溢出那么多内存。

      如果您确实需要创建足够的数据来填充这么多内存,那么您可以在 PHP.ini 中修改最大内存限额,但这不太可能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-22
        • 2017-01-11
        • 2013-03-21
        • 1970-01-01
        相关资源
        最近更新 更多