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

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

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条)

报告相同问题?