You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过PHP switch在不同函数中修改变量值?

问题:如何在特定函数中修改变量并在调用方获取值?

我希望在特定函数中修改变量的值,以下是相关代码示例:

function display_content(){
    switch (function) {
        case "recipe_list_dishes()":
            $dish_type = "'dishes'";
        break;
        case "recipe_list_desserts()":
            $dish_type = "'desserts'";
        break;
        case "recipe_list_snacks()":
            $dish_type = "'snacks'";
        break;
    }
}

function recipe_list_dishes() {
    display_content();
    echo $dish_type; // 预期值为'dishes'
}

请问这种实现方式可行吗?


回答

这种写法不可行,核心问题有两个:

  1. 语法错误:switch里的function是PHP关键字,不能直接用来获取调用函数的名称,原代码的判断逻辑根本无法执行。
  2. 变量作用域问题:$dish_type是display_content内部的局部变量,调用它的recipe_list_dishes函数无法直接访问这个变量,执行echo $dish_type会直接报错。

下面给你几种可行的实现方式:

方案一:让函数返回对应值(推荐)

用__FUNCTION__魔术常量获取当前函数名,传递给display_content,让它返回对应值,调用方接收后使用:

function display_content($func_name){
    switch ($func_name) {
        case "recipe_list_dishes":
            return "'dishes'";
        case "recipe_list_desserts":
            return "'desserts'";
        case "recipe_list_snacks":
            return "'snacks'";
        default:
            return "";
    }
}

function recipe_list_dishes() {
    $dish_type = display_content(__FUNCTION__);
    echo $dish_type; // 输出'dishes'
}

方案二:引用传递变量

将$dish_type以引用(&)的方式传入display_content,函数内直接修改变量值,调用方就能拿到修改后的结果:

function display_content(&$dish_type, $func_name){
    switch ($func_name) {
        case "recipe_list_dishes":
            $dish_type = "'dishes'";
            break;
        case "recipe_list_desserts":
            $dish_type = "'desserts'";
            break;
        case "recipe_list_snacks":
            $dish_type = "'snacks'";
            break;
    }
}

function recipe_list_dishes() {
    $dish_type = "";
    display_content($dish_type, __FUNCTION__);
    echo $dish_type; // 输出'dishes'
}

方案三:直接在调用函数内赋值(逻辑简单时更直观)

如果只是简单的函数与值的对应关系,没必要额外封装函数,直接在各自函数内赋值即可:

function recipe_list_dishes() {
    $dish_type = "'dishes'";
    echo $dish_type;
}

function recipe_list_desserts() {
    $dish_type = "'desserts'";
    echo $dish_type;
}

内容的提问来源于stack exchange,提问作者Astw41

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:24:48