Skip to content

Instantly share code, notes, and snippets.

@iluuu1994
Created June 14, 2020 18:15
Show Gist options
  • Save iluuu1994/bdc6babcae6e1b510c3530953974b729 to your computer and use it in GitHub Desktop.
Save iluuu1994/bdc6babcae6e1b510c3530953974b729 to your computer and use it in GitHub Desktop.
Partial POC
<?php
function sum(int $a, int $b, &$c) {
$c = $a + $b;
return $c;
}
function reflection_param_to_string(\ReflectionParameter $reflectionParam, bool $useList = false) {
$string = '';
if (!$useList && $reflectionParam->hasType()) {
$string .= (string) $reflectionParam->getType() . ' ';
}
if ($reflectionParam->isPassedByReference()) {
$string .= '&';
}
$string .= '$' . $reflectionParam->getName();
if (!$useList && $reflectionParam->isDefaultValueAvailable()) {
$string .= ' = ' . var_export($reflectionParam->getDefaultValue(), true);
}
return $string;
}
function create_partial_closure($callable, array $placeholderPositions)
{
$reflection = new ReflectionFunction($callable);
$reflectionParams = $reflection->getParameters();
$outerParamList = [];
$innerParamList = [];
$innerUseList = [];
$innerArgList = [];
foreach ($reflectionParams as $i => $reflectionParam) {
$paramString = reflection_param_to_string($reflectionParam);
if (in_array($i, $placeholderPositions, true)) {
$outerParamList[] = $paramString;
$innerUseList[] = reflection_param_to_string($reflectionParam, true);
} else {
$innerParamList[] = $paramString;
}
$innerArgList[] = '$' . $reflectionParam->getName();
}
$outerParamString = implode(', ', $outerParamList);
$innerParamString = implode(', ', $innerParamList);
$innerUseString = implode(', ', $innerUseList);
$innerArgString = implode(', ', $innerArgList);
$eval = <<<PHP
return function (callable \$callable, $outerParamString) {
return function ($innerParamString) use (\$callable, $innerUseString) {
return \$callable($innerArgString);
};
};
PHP;
return eval($eval);
}
$c = null;
$partial_call = create_partial_closure('sum', [1, 2]);
$partial_call_intermediate = $partial_call('sum', 1, $c);
$result = $partial_call_intermediate(10);
var_dump($c);
var_dump($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment