dongyongyu0789 2015-11-01 17:16
浏览 29
已采纳

为什么我不能访问这个全局变量?

I of course tried it with out the $GLOBALS and still no go. Is my syntax correct. My understanding is that $DB_USER is in the global scope.

<?php
    $DB_USER = 'foo';
    class Database
    {
        // this does not work
        private $DB_USER =              $GLOBALS['DB_USER'];
        private $DB_PASS =              'foob';
        private $DB_DRIVER =            'foob_foob';
        // ...
  • 写回答

3条回答 默认 最新

  • duangouhui0446 2015-11-01 17:36
    关注

    You are calling $DB_USER from inside of your class method, which means you are actually calling the variable from the local scope (within the class). To fix this, just tell PHP that you're looking for the global variable by adding global $DB_USER inside of your methods where it will be used (or use your constructor to add it to the class scope):

    class Database
    {  
        private $DB_USER =              '';
        private $DB_PASS =              'foob';
        private $DB_DRIVER =            'foob_foob';
        // snip
    
    
       // Method 1: Add the variable to the class scope with the constructor        
       public function __construct() 
       {
          global $DB_USER;
          $this->DB_USER = $DB_USER;
       }
    
    
       // Method 2: tell PHP that you want the global variable in your methods
       public function foo() 
       {
          $global $DB_USER;
          ...
        }
    

    With method 1, you can now call $this->DB_USER instead of $GLOBALS['DB_USER'].

    With method 2, you add global $DB_USER to each, and then just use $DB_USER.

    For more information see http://php.net/manual/en/language.variables.scope.php

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

报告相同问题?

悬赏问题

  • ¥15 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?