doubi1713 2011-05-25 16:25
浏览 75
已采纳

无法访问包含文件中的全局变量

I am having an unexpected issue with scope. The include documentation (also applies to require_once) says the required file should have access to all variable at the line it was required.

For some reason I am not able to access a class instantiated with global scope inside a function that was required in.

Would anyone know why? I am obviously missing something.

I got it working through a reference to $GLOBALS[], but I still want to know why it is not working.

UPDATE:
The error I am getting is:

Fatal error: Call to a member function isAdmin() on a non-object in <path>.php on <line>

Code:

$newClass = new myClass();

require_once("path to my file");

----- inside required file -----
function someFunction() {
     $newClass->someMethod(); // gives fatal error. (see above).
}
  • 写回答

2条回答 默认 最新

  • dongyang2229 2011-05-25 16:32
    关注

    Functions define a new scope, so inside a function you cannot access variables in the global scope.

    Variable Scope

    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

    About included files, the manual states:

    When a file is included, the code it contains inherits the variable scope of the line on which the include occurs.

    So if you include something in a function, the included file's scope will be that of the function's.

    UPDATE: Looking at your code example edited into the question, global $newClass; as the first line of the function should make it working.

    $newClass = new myClass();
    require_once("path to my file");
    
    ----- inside required file -----
    function someFunction() {
         global $newClass;
         $newClass->someMethod(); 
    }
    

    Be aware though that using global can quickly make your code more difficult to maintain. Don't rely on the global scope, you can pass the object to the function as a parameter, or use a Singleton/Registry class (some tend to argue against the latter, but depending on the case it can be a cleaner solution).

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

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错