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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?