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 PdfiumViewer pdf转图片
  • ¥15 利用Java连接API接口总是出问题
  • ¥15 请教一个关于镜头标定,棋盘格格子大小的问题(畸变测试)
  • ¥15 安装GroudingDINO RuntimeError: Error compiling objects for extension
  • ¥15 关于推送项目到github的问题
  • ¥15 急!C++指针编写相关的问题
  • ¥15 kerberos身份认证配置问题
  • ¥30 用python写一个多签情况下波场的代理资源和回收资源
  • ¥15 matlab学期例题代码答疑
  • ¥15 在线手电筒追加按钮JS