Jump to content

Recommended Posts

I have an array. I would like to use the values of the array as the parameter list when calling a function. Here is an example, where what I seek is $mystery_function_x:

 

$parameters = array('1234.45', 1);
$function = 'number_format';

// I want the same result as: 
//number_format('1234.45', 1);
  $function( $mystery_function_x($parameters) );

 

This needs to work for calling different functions, accepting different numbers of parameters, so I cannot reference the parameters directly with subscript notation. I'm looking for something like 'array_values', only returning a list (like 'values' in perl.) Or perhaps I'm thinking about this in the wrong way, but I feel like I'm overlooking the obvious.

 

Any insight appreciated. Thanks!

:)

 

<?php
$parameters = array('1234.45', 1);
$function = 'number_format';

if (count($parameters) == 1) 
{
    $function($parameters[0]);
} 
else if (count($parameters) == 2) 
{
    $function($parameters[0], $parameters[1]);
}
else if (count($parameters) == 3) 
{
    $function($parameters[0], $parameters[1], $parameters[2]);
}
?>

 

I think I have seen this method used in a few frameworks, so there is a good chance it is the only way to do it.

@premisio: unfortunately that hits the same problem.

 

@flyhoney: that's close to what I ended up having to do, using subscript notation to access the values directly, although I built the code string and eval'd it so as not to limit it to a particular number of parameters. I avoid eval if possible, but at least I'm not interpolating anything into the eval'd code.

 


$parameters = array('1234.45', 1);
$function = 'number_format';
$functioncall = 'return( $function( ';
$paramprep = array();
for ($x=0 ; $x < count($parameters); $x++ ) $paramprep[] = '$parameters['.$x.']';
$functioncall .= implode(', ', $paramprep) . ' ) );';
eval($functioncall);

 

Thanks for taking a look.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.