dongtidai6519 2011-05-01 19:13
浏览 56
已采纳

PHP函数不会保存变量

I have this php function that I created that is basically a switch statement. For each case, the $team_image variable is saved to a different value. It looks a little something like this:

function teamImage($team)
{
    switch($team)
    {
        case "Baltimore Orioles":

            $team_image = "orioles";

        case "New York Yankees":

            $team_image = "yankees";

        case "Toronto Blue Jays":

            $team_image = "bluejays";

You get the idea. However, when I call on the function and try to use the $team_image variable in other parts of my code, it doesn't work because apparently, the variable is still undefined. any thoughts?

Thanks,

Lance

  • 写回答

7条回答 默认 最新

  • dsfsfsfsfs55656 2011-05-01 19:18
    关注

    As you're only setting the $team_image inside the teamImage function, it will only exist with that function's "scope". (In general, variables, etc. will always exist in as narrow a scope as possible, which is good in terms of encapsulation. (Encapsulation being a key benefit of object orientated programming, etc. which you may go on to discover as you learn more.)

    As such, you should return the $team_image value from the teamImage function and set it as follows:

    function teamImage($team) {
    
        $team_image = NULL;
    
        switch($team) {
           ...
        }    
    
        return $team_image;
    }
    
    $team_image = teamImage($team);
    

    An alternative would be to define the $team_image variable within the teamImage function as a global by adding the line global $team_image; at the beginning of the function, but this isn't considered good practice.

    Additionally, you should break; each case code block within your switch statement as otherwise you'll simply end up setting $team_image with the value assigned in your final case. (i.e.: If you don't break each statement, code flow will continue into the next.) See the switch PHP manual page for full details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集