Victor Sheckels
Victor Sheckels

Reputation: 21

Creating a function from a variable

I am attempting to run a function named from a variable. There is no syntax error. Temperature is not returned. I don't know for certain if the problem is with the function itself or the eval. Variations on the eval theme have not worked so far.

function getBtemp($lum, $sub){
    $tempsB = array(
         "V" => array( 30000, 25400, ... ),
         "III" => array( 29000, 24000, ... ),
         "I" => array( 26000, 20800, ... ) );
    if($lum == "VI"){ $lum = "V"; }
    else if($lum == "IV"){ $lum = "III"; }
    else if($lum == "II" || $lum == "Ib" || $lum == "Ia" ){ $lum = "V"; }
    return $tempsB['$lum']['$sub']; }

// Variables:

$spectralclass = "B";
$luminosityclass = "V";
$subclass = 5;

// Needed:

$temp = getBtemp($luminosityclass, $subclass);

// Functions are named from spectral class, e.g. get.$spectralclass.temp()
// Attempt:

$str = "$temp = get".$spectralclass."temp($luminosityclass, $subclass);";
eval($str);

Upvotes: 0

Views: 68

Answers (4)

cHao
cHao

Reputation: 86506

You might be better off doing something like

$functionName = 'get' . $spectralclass . 'temp';
$temp = $functionName($luminosityclass, $subclass);

This is what the PHP manual calls a "variable function". In most cases PHP lets you treat a string variable as a function name, and doing so is a bit safer (more restrictive, less error-prone) than eval.

Upvotes: 2

Gabriel Santos
Gabriel Santos

Reputation: 4974

You need to pass parameters after set function name. See a sample:

function getAtemp($a = 'default') {
    echo $a;
}

$name = 'Trest';
$function = 'A';

$temp = 'get' . $function . 'temp';

echo($temp('teste'));

Additionally, read from Eric Lippert: Eval is Evil

Upvotes: 1

Menztrual
Menztrual

Reputation: 41597

Try doing this:

$func = 'get'.$spectralclass.'temp';

$temp = $func($luminosityclass, $subclass);

Upvotes: 4

AdrienBrault
AdrienBrault

Reputation: 7745

Replace the following line:

$str = "$temp = get".$spectralclass."temp($luminosityclass, $subclass);";

by

$str = '$temp = get'.$spectralclass.'temp($luminosityclass, $subclass);';

or

$str = "\$temp = get".$spectralclass."temp(\$luminosityclass, \$subclass);";

See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double

Upvotes: 0

Related Questions