PHP-根据调用哪个变量来执行函数

时间:2018-08-02 16:26:31

标签: php function

我有2个功能完全相同的功能,但变量不同:

function checkRights($user){
    if($user['rights'] == 'DEVELOPER'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/Developer.png" alt="Developer Icon"/>';
    } else if($user['rights'] == 'ADMINISTRATOR'){
        $GLOBALS['crowncol'] = "#D0CE2C";
        echo' <img src="/admin.png" alt="Administrator Icon"/>';
    } else if($user['rights'] == 'MODERATOR'){
        $GLOBALS['crowncol'] = "#FFCC00";
        echo' <img src="mod.png" alt="Moderator Icon"/>';
    } else if($user['rights'] == 'DONATOR'){
        $GLOBALS['crowncol'] = "#FF0000";
        echo' <img src="donator.png" alt="Donator Icon"/>';
    } else if($user['rights'] == 'SUPER_DONATOR'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/superdonator.png" alt="Super Donator Icon"/>';
    } else if($user['rights'] == 'LEGENDARY_DONATOR'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/respecteddonator.png" alt="Legendary Donator Icon"/>';
    } else if($user['rights'] == 'PLAYER'){
        $GLOBALS['crowncol'] = "#037AAC";
    }
}
function checkPlayerRights($player){
    if($player['rights'] == 'DEVELOPER'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/Developer.png" alt="Developer Icon"/>';
    } else if($player['rights'] == 'ADMINISTRATOR'){
        $GLOBALS['crowncol'] = "#D0CE2C";
        echo' <img src="/admin.png" alt="Administrator Icon"/>';
    } else if($player['rights'] == 'MODERATOR'){
        $GLOBALS['crowncol'] = "#FFCC00";
        echo' <img src="/mod.png" alt="Moderator Icon"/>';
    } else if($player['rights'] == 'DONATOR'){
        $GLOBALS['crowncol'] = "#FF0000";
        echo' <img src="/donator.png" alt="Donator Icon"/>';
    } else if($player['rights'] == 'SUPER_DONATOR'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/superdonator.png" alt="Super Donator Icon"/>';
    } else if($player['rights'] == 'LEGENDARY_DONATOR'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/respecteddonator.png" alt="Legendary Donator Icon"/>';
    } else if($player['rights'] == 'PLAYER'){
        $GLOBALS['crowncol'] = "#037AAC";
    }
}

我想知道是否可以将它们组合成一个名为checkRights的函数,这样我要做的就是执行一个函数,但调用我希望它运行哪个变量。

例如:checkRights($user);checkRights($player);

1 个答案:

答案 0 :(得分:2)

构建一个带有一个参数的函数(无论如何您已经做过):

function checkRights($obj){
    if($obj['rights'] == 'DEVELOPER'){
        $GLOBALS['crowncol'] = "#9A9A9A";
        echo' <img src="/Developer.png" alt="Developer Icon"/>';
    } 
    // ...
    else if($obj['rights'] == 'PLAYER'){
        $GLOBALS['crowncol'] = "#037AAC";
    }
}

现在像这样调用函数:

checkRights($player);
checkRights($user);