dsb53973 2012-06-18 16:09
浏览 96
已采纳

PHP函数使用外部变量

function parts($part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo($tructure . $part . '.php'); 
}

This function uses a variable $site_url that was defined at the top of this page, but this variable is not being passed into the function.

How do we get it to return in the function?

  • 写回答

4条回答 默认 最新

  • dtrotfd1012 2012-06-18 16:11
    关注

    Add second parameter

    You need to pass additional parameter to your function:

    function parts($site_url, $part) { 
        $structure = 'http://' . $site_url . 'content/'; 
        echo $structure . $part . '.php'; 
    }
    

    In case of closures

    If you'd rather use closures then you can import variable to the current scope (the use keyword):

    $parts = function($part) use ($site_url) { 
        $structure = 'http://' . $site_url . 'content/'; 
        echo $structure . $part . '.php'; 
    };
    

    global - a bad practice

    This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

    For the completeness sake here is the solution using global:

    function parts($part) { 
        global $site_url;
        $structure = 'http://' . $site_url . 'content/'; 
        echo($structure . $part . '.php'); 
    }
    

    It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

    Suggested reading:

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?