2017-09-26 38 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() { 

     } 
    } 
    ?> 
相關問題