php 實現golang defer延遲執行(先進後出)

my38778570發表於2023-02-14
<?php

echo '開始 <br />';
$num = '1 <br />';
${__LINE__} = defer(function () use ($num) {
   echo $num;
});
echo ${__LINE__};

$num = '2 <br />';
${__LINE__} = defer(function () use ($num) {
    echo $num;
 });


 $num = '3 <br />';
 ${__LINE__} = defer(function () use ($num) {
     echo $num;
  });

echo '結束 <br />';

 function defer(callable $cb)
{

    return new class($cb)
    {
        public function __construct($fn)
        {
            $this->fn = $fn;
        }

        public function __destruct()
        {
            ($this->fn)();
        }
    };
}

輸出

開始
結束
3
2
1
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章