dopod0901 2010-01-23 14:07
浏览 52
已采纳

PHP:函数甚至不存在变量

I've noticed an annoying peculiarity in PHP (running 5.2.11). If one page includes another page (and both contain their own variables and functions), both pages are aware of each others' variables. However, their functions seem to be aware of no variables at all (except those declared within the function).

My question: Why does that happen? How do I make it not happen, or what's a better way to go about this?

An example of what I'm describing follows.

Main page:

<?php
$myvar = "myvar.";
include('page2.php');

echo "Main script says: $somevar and $myvar
";
doStuff();
doMoreStuff();
function doStuff() {
    echo "Main function says: $somevar and $myvar
";
}
echo "The end.";
?>

page2.php:

<?php
$somevar = "Success!";

echo "Included script says: $somevar and $myvar
";

function doMoreStuff() {
    echo "Included function says: $somevar and $myvar
";
}
?>

The output:

Included script says: Success! and myvar.
Main script says: Success! and myvar.
Main function says: and
Included function says: and
The end.

Both pages output the variables just fine. Their functions do not.
WRYYYYYY

  • 写回答

3条回答 默认 最新

  • doumanju2533 2010-01-23 14:10
    关注

    You need to use global before using outside-defined variables in a function scope:

    
    function doStuff() {
        global $somevar, $myvar;
        echo "Main function says: $somevar and $myvar
    ";
    }
    

    More detailed explanation provided at: http://us.php.net/manual/en/language.variables.scope.php

    As comments & other answers pointed out accurately, globals can be evil. Check out this article explaining just why: http://my.opera.com/zomg/blog/2007/08/30/globals-are-evil

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

报告相同问题?

悬赏问题

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