0

我正在尝试使用 php 变量变量调用函数。你会在我的代码中看到function mainFunction()。如果不可能这样做,有没有更好的方法可以避免更多的代码?我希望它能以这种方式工作。

<?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>';
}
?>
4

5 回答 5

3

解决此问题的一种方法是使用 PHP 的 call_user_func 函数。这是修改后的代码(它还删除了全局变量):

代码示例

<?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>';
}

输出

当我运行此代码时,它会产生以下输出:

This is mainFunction 
This is example two 
于 2013-05-29T05:04:26.690 回答
1

Try with $exampleFunction(); instead of $$exampleFunction();

OR

use call_user_func($exampleFunction)

于 2013-05-29T04:41:24.900 回答
1

check this way :-

function mainFunction() {
global $exampleFunction;
echo 'This is mainFunction <br>';
$exampleFunction();
 }
于 2013-05-29T04:43:15.927 回答
1

只使用$exampleFunction,不使用$$

<?php
function mainFunction() {
    global $exampleFunction;
    echo 'This is mainFunction <br>';
    $exampleFunction();
}
?>

请参阅变量函数手册,而不是变量变量

PS:另外,我建议$exampleFunction使用argumentofmailFunction,而不是使用globals。

于 2013-05-29T04:40:59.193 回答
1

试试喜欢

if ( $a == $b ) {
   $exampleFunction = exampleOne();
} else {
   $exampleFunction = exampleTwo();
}

你的函数应该像

function exampleOne() {
    return 'This is example one <br>';
}

function exampleTwo() {
    return 'This is example two <br>';
}

或者,如果您想通过变量调用它们,请尝试替换为

function mainFunction() {
   global $exampleFunction;
     echo 'This is mainFunction <br>';
     $exampleFunction();
 }
于 2013-05-29T04:41:21.840 回答