PHP code example of mostka / defer

1. Go to this page and download the library: Download mostka/defer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mostka / defer example snippets


// Contents returns the file's contents as a string.
function contents($filename) {
    $f = fopen($filename, "r");
    if ($f === false) {
        throw new Exception("Error opening the file");
    }
    $defer = defer(fclose(...),$f);  // fclose will run when we're finished.

    $result = ""; 

    while (($buffer = fread($f, 100)) !== false) {
        $result .= $buffer; 
    }

    if (feof($f) === false) {
        // $f will be closed if we return here.
        throw new Exception("Error reading the file");
    }

    // $f will be closed if we return here.
    return $result;
}

function foo($a){
    echo "in defer {$a}".PHP_EOL;
}
function a() {
    echo "before defer".PHP_EOL;
    $defer = defer(foo(...),1);
    $defer(foo(...),2);
    $defer(foo(...),3);
    echo "after defer".PHP_EOL;
};

echo "start".PHP_EOL;
a();
echo "end".PHP_EOL;

function a(){
    $i=0;
    $_ = defer(printf(...),$i);
    $i++;
}

function b(){
    $defer = defer();
    for($i=0;$i<4;$i++){
        $defer(printf(...),$i);
    }
}

function c() {
    $i=1;
    $o=new \stdClass();
    $o->i=2;
    $defer = defer(function () use (&$i, $o) {
        $o->i++;
        $i++;
    });

    $i++;
    return [$i,$o];
}
list($i,$o) = c();
echo "{$i}-{$o->i}".PHP_EOL;

namespace test;

(){}
class Foo{
    public function myMethod(){}
}
function a(){
    // defer custom function without parameter
    // function name must be with his namespace
    $defer = defer('test\myFunc');
    // defer function with one parameter
    $defer(printf(...),"test");
    // defer function with more parameters
    $defer('printf',"%s-%s",10,12);
    // defer with anonymous function
    $defer(function (){});
    $func = function (){};
    $defer($func);
    //defer method
    $foo = new Foo();
    $defer([$foo,'myMethod']);
}
a();