2012-02-24 38 views
5

すでに設定されているregister_shutdown_functionスタックを上書きすることはできますか?この場合register_shutdown_function上書き

function f1(){ 
    echo "f1"; 
} 
function f2(){ 
    echo "f2"; 
} 
register_shutdown_function("f1"); 
echo "actions here"; 
register_shutdown_function("f2"); 
call_to_undefined_function(); // to "produce" the error 

私は唯一の呼び出しf2()にスクリプトをしたい:ような何か。これは可能ですか? register_shutdown_function()php doc pageから

答えて

3

これはできません。 PHPにはremove_user_shutdown_function PHPAPI関数がありますが、これはユーザランドコードには公開されていません。

+0

リンクがダウンしている.... – Pacerier

+0

とスコットなど指摘されている、それは可能です – vivoconunxino

2

register_shutdown_functionに複数の呼び出しは()することができ、各 は、それらが登録されたと同じ順序で呼び出されます。登録済みシャットダウン機能内で exit()を呼び出した場合、処理は完全に終了し、登録シャットダウン機能は呼び出されません。

したがって、関数f2を呼び出す場合は、例外ハンドラのexit()呼び出しに渡すことができます。 register_shutdown_function()を複数回呼び出すと、最後に登録された関数だけでなく、すべての関数が順番に呼び出されます。 unregister_shutdown_function()のようなものはないように思われるので、これが私の提案です。

0

私もこの問題を抱えている、と私はこれを解決:あなたはまっすぐにそれを行うことはできませんが、回避策は常にあります

function f1(){ 
if (defined('CALL1') && CALL1===false) return false; 
echo "f1"; 
} 
function f2(){ 
    echo "f2"; 
} 
register_shutdown_function("f1"); 
echo "actions here"; 
define('CALL1', false); 
register_shutdown_function("f2"); 
call_to_undefined_function(); 
3

$first = register_cancellable_shutdown_function(function() { 
    echo "This function is never called\n"; 
}); 

$second = register_cancellable_shutdown_function(function() { 
    echo "This function is going to be called\n"; 
}); 

cancel_shutdown_function($first); 

出力:

$ php test.php 
This function is going to be called 

The code

使用例

function register_named_shutdown_function($name, $callback) 
{ 
     static $callbacks = []; 
     $callbacks[$name] = $callback; 

     static $registered; 
     $registered || $registered = register_shutdown_function(function() use (&$callbacks) { 
       array_map(function ($callback) { 
         call_user_func($callback); 
       }, $callbacks); 
     }) || true; 
} 

register_named_shutdown_function("first", function() { 
     echo "Never executed\n"; 
}); 

register_named_shutdown_function("second", function() { 
     echo "Secondly executed\n"; 
}); 

register_named_shutdown_function("first", function() { 
     echo "Firstly executed\n"; 
}); 

出力:10

function register_cancellable_shutdown_function($callback) 
{ 
     return new cancellable_shutdown_function_envelope($callback); 
} 

function cancel_shutdown_function($envelope) 
{ 
    $envelope->cancel(); 
} 

final class cancellable_shutdown_function_envelope 
{ 
     private $callback; 

     public function __construct($callback) 
     { 
       $this->callback = $callback; 
       register_shutdown_function(function() { 
         $this->callback && call_user_func($this->callback); 
       }); 
     } 

     public function cancel() 
     { 
       $this->callback = false; 
     } 
} 
1

その他のオプションは、次の機能を使用することです

Firstly executed 
Secondly executed