note 113150 deleted from function.create-function by cmb
| From: | cmb@php.net | Date: | Thu, 07 Jul 2022 14:40:10 +0000 |
| Subject: | note 113150 deleted from function.create-function by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218924@lists.php.net to get a copy of this message | ||
Note Submitter: ionix at NOSPAM dot post dot com
----
I experimented a bit in creating a lambda function using a variable amount of arguments. While I
couldn't find an efficient way to create a random bit of code, I was able to get it to behave
as a front end for existing functions (as well as user-defined of course).
The code required me to use the dreaded eval() function to get it to use a variable amount of
parameters, so be sure that all input is thoroughly cleaned if derived from the user.
<?php
function run_function( $function )
{
// Get Arguments, Unset Exisitng Parameter
$params = func_get_args();
unset( $params[0] );
if( ( $count = count( $params ) ) > 0 )
{
$args = '$a';
$inc = 'b';
// Create Argument String - Formats as '$a, $b, $c' Per Number of Arguments
for( $x = 1; $x < $count; $x++ )
{
$args .= ', $' . $inc;
$inc++;
}
// Create Lambda Function and Format Paramters
$lambda = create_function( $args, 'return ' . $function . '(' . $args .
');' );
$params = "'" . implode('\', \'', $params) .
"'";
// Build and Evaluate Function with Parameters
$eval = '$return = $lambda(' . $params . ');';
eval($eval);
return $return;
}
else
{
return false;
}
}
?>
For most applications you would be better off calling the function normally. Perhaps this little
proof of concept may find some use if adapted to work by someone who requires it.