...

View Full Version : Function name in string to be evaluated



mathceleb
03-11-2010, 09:06 PM
I did some research on using eval and call_user_func, and neither works from what I've tried. Code is below:


function qnum()
{
$a=1;
$b=2;
return $a . "#" . $b;
}

$str="qnum()";
$q=eval($str);
echo "q = " . $q . "<br />";

I want the echo line to spit out 1#2.

Any ideas?

mlseim
03-11-2010, 10:18 PM
The idea of using a function is to pass it some variable(s) and process them.
A solution, or "answer" is returned.

Like this:


<?php

// test variables
$a=1;
$b=2;

$str=qnum($a,$b);
echo $str . "<br />";

// increment them
$a++;
$b++;

// and echo them out again ...
echo qnum($a,$b);

// The function to take-in any two numbers and spit-out the result ... example: 1#2
function qnum($x,$y){
return $x . "#" . $y;
}

?>


This is the result of the script above:
1#2
2#3



.

Fou-Lu
03-11-2010, 10:29 PM
I hate eval so much. Its the only function that I constantly cause a parse error on every time I first write it. Me hates.
Eval is assigned differently, I can't say I've ever called a function from it off hand, but I believe that it will only return a non-void result if 'return' is actually used within it (not the function it calls). So eval would be:


eval("\$q = qnum();");

Yeah that looks right. I'll bet the first run will fail though O.o hah

Call_user_func is what you'd want. Eval is as dangerous as it is annoying:


$q = call_user_func('qnum');

Much easier. The only time you need to do this is on a <5.3 system with a callback/delegate/function pointer:


function myFunc($data, $callback)
{
return call_user_func($callback, $data);
}


Otherwise, there is no reason whatsoever to call a known function with call_user_func.

mlseim
03-11-2010, 10:31 PM
I guess I totally missed the point of post #1, sorry.

mathceleb
03-11-2010, 10:43 PM
I tried the following:



$str="qnum";
$q1=call_user_func($str);
echo "q1 = " . $q1 . "<br />";


q1 spits out nothing.

mathceleb
03-11-2010, 10:54 PM
Cancel that order, it worked.

I had one tick mark out of place. Thanks everybody!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum