Reputation: 1926
I'm trying to call a function with a php variable variable. You'll see in my code in function mainFunction()
. If it's not possible to do it this way, is there a better way to do it, that avoids any more code? I wish it would work this way.
<?php
$a = 1;
$b = 1;
if ( $a == $b ) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction();
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$$exampleFunction();//Here's where I'm stuck.
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
?>
Upvotes: 0
Views: 122
Reputation: 12168
Use just $exampleFunction
, without $$
:
<?php
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
?>
See manual of variable functions, not variable variables.
P.S.: Also, I suggest $exampleFunction
to be an argument
of mailFunction
, rather than use global
s.
Upvotes: 1
Reputation: 111
A way to solve this problem would be to use PHP's call_user_func function. Here is the modified code (it also removes the global variable):
<?php
$a = 1;
$b = 1;
// I'm just using this to hold the function name,
// to get rid of the global keyword. It will be passed
// as an argument to our mainFunction()
$exampleFunction = '';
if ($a == $b) {
$exampleFunction = 'exampleOne';
} else {
$exampleFunction = 'exampleTwo';
}
//----------------------------------------------
mainFunction($exampleFunction);
function mainFunction($func) {
echo 'This is mainFunction <br>';
// Use PHP's call_user_func. We are also checking to make sure
// the function exists here.
if (function_exists($func)) {
// This will call the function.
call_user_func($func);
}
}
function exampleOne() {
echo 'This is example one <br>';
}
function exampleTwo() {
echo 'This is example two <br>';
}
When I run this code, it produces the following output:
This is mainFunction
This is example two
Upvotes: 3
Reputation: 4142
check this way :-
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Upvotes: 1
Reputation: 6192
Try with $exampleFunction();
instead of $$exampleFunction();
OR
use call_user_func($exampleFunction)
Upvotes: 1
Reputation: 28763
Try like
if ( $a == $b ) {
$exampleFunction = exampleOne();
} else {
$exampleFunction = exampleTwo();
}
and your functions should return like
function exampleOne() {
return 'This is example one <br>';
}
function exampleTwo() {
return 'This is example two <br>';
}
OR if you want to call them through the variable try to replace like
function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
}
Upvotes: 1