duanke6057 2009-12-14 17:51
浏览 45
已采纳

来自其他文件的PHP变量返回为NULL

In one PHP file, I have this code:

require_once $_SERVER['DOCUMENT_ROOT'] . '/custom/functions.php';
global $testVar;
var_dump($testVar);

In the functions.php file, I have this at the beginning, followed by a few other functions:

function pr($s) {
    echo '<pre>', htmlspecialchars(print_r($s,true)), '</pre>';
}

$testVar = 'hello world';

When running the first file, the variable comes back as NULL. I added the global bit but it shouldn't be necessary. This is part of a Joomla module but I've never had problems including files before, it should just work like regular PHP. Why might this be happening?

  • 写回答

2条回答 默认 最新

  • dongya1875 2009-12-14 18:03
    关注

    First, try to use Joomla's path constants such as JPATH_BASE instead of $_SERVER['DOCUMENT_ROOT']. Joomla has a lot of useful constants, check it's documentation.

    I've read your answer, and reading php documentation I tried to find a reason to why you need to use global keyword twice.

    First, Variable scope.

    The scope of a variable is the context within which it is defined. For the most 
    part all PHP variables only have a single scope.
    
    (...)
    
    However, within user-defined functions a local function scope is introduced. 
    Any variable used inside a function is by default limited to the local 
    function scope. 
    

    The variable isn't in a function scope, so that's why we thought the NULL was a strange behavior.

    But then I read include and found something interesting:

    (...)
    Any variables available at that line in the calling file will be available 
    within the called file, from that point forward. However, all **functions** 
    and **classes** defined in the included file have the global scope. 
    

    I can't see any mention about the variables being global in this paragraph. So,it seens that, being cumbersome or not, your solution is the right thing to do when you want to use global variables like that.

    In your situation, if doing this is cumbersome, I would create a simple class. If you have just helper functions in your file, create a class Util{} with a lot of methods and $testVar as an attribute.

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

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比