2017-09-26 39 views
0

我需要这样的东西如何使处理程序专门用于在php中出现内存不足的情况?

register_error_handler(MEMORY_LEAK, 'function_that_handles_that'); 

是否有这样的事?或者我是否必须手动检查内存以执行某种内存清理?我有解析7000个条目后可以获得1GB内存的情况,但不知何故,我知道如何减少函数中当前的内存使用量,但我不想每次都在循环中调用它。

+0

我认为内存错误不可捕捉(您需要更多的内存来抛出错误)。尝试更明智地管理你的数据。 – Justinas

+0

事实错误不可捕捉并不意味着没有解决方法... – azurinko

+0

无论如何它已经分配了一些无用的东西,它被分成小于32MB:D – azurinko

回答

0

所以调用$ memcheck-> run()在循环的beging可以以某种方式...解决这种情况。 //未测试

<?php 
    namespace utility; 
    class memcheck { 

     protected static $instance; 

     public static function i() { 
      if (!isset(static::$instance)) { 
       static::$instance = new static(); 
      } 
      return static::$instance; 
     } 

     private function __construct() { 
      $this->cleanup_after = (str_replace('m', '', strtolower($GLOBALS['s']['memory']['cleanup_after'])))*1024*1024; 
      $this->shutdown_after = (str_replace('m', '', strtolower($GLOBALS['s']['memory']['max'])))*1024*1024; 
     public function run() { 
      $allocated_memory = memory_get_usage(true); 
      $cleanup = ($allocated_memory > $this->cleanup_after); 
      $shutdown = ($allocated_memory > $this->shutdown_after); 
      $allocated_memory = $allocated_memory/1024/1024; 
      if($cleanup) { 
       if($shutdown) { 
        echo 'Too much memory in use '.$allocated_memory.'M -> shutting down'; 
        $this->shutdown(); 
       } else { 
        echo 'Too much memory in use '.$allocated_memory.'M -> cleaning up'; 
        $this->cleanup(); 
        $allocated_memory = memory_get_usage(true)/1024/1024; 
        echo 'Allocated memory reduced to '.$allocated_memory/1024/1024.; 
       } 
      } 

     } 
     private function shutdown() { 

     } 
     private function cleanup() { 

     } 
    } 
    ?> 
相关问题