Re: Call function and get return...
| From: | Lars Torben Wilson | Date: | Wed, 16 Aug 2000 08:54:28 +0000 |
| Subject: | Re: Call function and get return... | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-11954@lists.php.net to get a copy of this message | ||
Martin Thoma writes:
> Hi Torben,
>
> thanks for your answer, but I got the same problem I told Soeren just
> bevore:
>
> echo $func();
>
> will deliever: "f2();" when calling doIt("f2();");
>
> (Unsing PHP 4.0.2pl)
>
> Any other ideas ?
>
> Regards
>
> Martin
Well, yes, it will. Unless you *really* have to call it like that,
calling it like DoIt("f2") does, indeed, work. If you cannot avoid
calling it like DoIt("f2();"), then you could rewrite DoIt() as:
function DoIt($func) {
$func = str_replace('();', '', $func);
if (function_exists($func)) {
echo $func();
}
}
...which will strip the parentheses and semicolon which don't work
with variable functions.
This works because when PHP sees a variable with parentheses on the
end, it will attempt to call the function whose name is contained in
the variable. For instance:
<?php
function foo() {
echo "In foo()<br>\n";
}
function bar($arg = '') {
echo "In bar(); argument was '$arg'.<br>\n";
}
$func = 'foo';
$func();
$func = 'bar';
$func('test');
?>
In order to have DoIt() return the returned value, just do this:
<?php
function DoIt($func) {
$func = str_replace('();', '', $func);
if (function_exists($func)) {
return $func();
}
}
echo DoIt("f2();");
?>
Cheers,
Torben
--
+----------------------------------------------------------------+
|Torben Wilson <torben@php.net> Netmill iTech|
|http://www.coastnet.com/~torben http://www.netmill.fi|
|Ph: 1 250 383-9735 torben@netmill.fi|
+----------------------------------------------------------------+