Skip to content

Instantly share code, notes, and snippets.

@rgpublic
Created November 11, 2019 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rgpublic/499071d10bfe067ffc271f60f75ec132 to your computer and use it in GitHub Desktop.
Save rgpublic/499071d10bfe067ffc271f60f75ec132 to your computer and use it in GitHub Desktop.
<?php
class SerializableClosure {
private $args;
private $code;
function __construct($args,$code) {
$this->args=$args;
$this->code=$code;
}
public function __invoke(&$arg1=null,&$arg2=null,&$arg3=null,&$arg4=null,&$arg5=null,&$arg6=null,&$arg7=null,&$arg8=null,&$arg9=null) {
$argstr=implode(",",$this->args);
$paras=[];
for ($k=1;$k<=count($this->args);$k++) $paras[]='$arg'.$k;
$paras=implode(",",$paras);
return eval('return (function ('.$argstr.') {'.$this->code.'})('.$paras.');');
}
}
$closure=new SerializableClosure(['&$a','&$b'],'$a++;$b++;return $a+$b;');
$a=7;$b=5;
echo $closure($a,$b)."\n";
echo $a."/".$b."\n";
echo "====\n";
$serialize=serialize($closure);
$new_closure=unserialize($serialize);
$a=7;$b=5;
echo $new_closure($a,$b)."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment