dounai1986 2010-03-09 19:45
浏览 60
已采纳

函数变量来自包含文件 - php

I haven't found a very good answer to my problem so I'm starting a new topic. I have the file english.php which has variables like $lang['fname'] = "First name";. Also I have header.php which includes english.php : include('english.php');. Now, header.php is included in another php page, let say addInfo.php. If I write in addInfo.php : echo $lang['fname']; it shows me "First name", but if i write a function in addInfo.php, as example function added () { echo $lang['fname'];} and then added(); (i tried also echo added()) it doesn't want to display the value("First name"). Does somebody know a solution for this sample(i think) problem. I'm ready to try all answers. Regards, StefanZ

  • 写回答

2条回答 默认 最新

  • douna1895 2010-03-09 19:56
    关注

    When you write this :

    function added () {
        echo $lang['fname'];
    } 
    

    PHP will search for a $lang variable that is local to the function :

    • it will not see the global one that's declared outside of the function.
    • and, as there is no $lang variable set, inside the function, $lang['fname'] will be null -- i.e. it will not display anything when echoed.


    To indicate to PHP that it should use the global variable from outside the function, you need to declare the variable as global, inside the function :

    function added () {
        global $lang;
        echo $lang['fname'];
    } 
    


    For more informations, you should read the Variable scope section of the PHP manual.

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?