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

时间:2015-11-01 17:16:06

标签: php

我当然尝试了$DB_USER并且仍然没有去。我的语法是否正确。我的理解是<?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'; // ... 在全球范围内。

fieldErrors

3 个答案:

答案 0 :(得分:2)

您正在从类方法内部调用$DB_USER,这意味着您实际上是从本地范围(类内)调用变量。要解决这个问题,只需告诉PHP您正在寻找全局变量,方法是在您将使用它的方法中添加global $DB_USER(或使用您的构造函数将其添加到类范围):

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;
      ...
    }

使用方法1,您现在可以拨打$this->DB_USER而不是$GLOBALS['DB_USER']

使用方法2,您可以为每个添加global $DB_USER,然后使用$DB_USER

有关详细信息,请参阅http://php.net/manual/en/language.variables.scope.php

答案 1 :(得分:0)

使用构造函数初始化varibale:

public function __constructor(){
    global $YOUR_VARIABLE;
    $DB_USER = $YOUR_VARIABLE;
}

答案 2 :(得分:0)

因此,您首先声明variables并在__construct方法中初始化它们

$DB_USER = 'foo';
class Database
{
    private $DB_USER,
    $DB_PASS,
    $DB_DRIVER;
    public function __construct(){
        $this->DB_USER = $GLOBALS['DB_USER'];
        $this->DB_PASS = 'foob';
        $this->DB_DRIVER = 'foob_foob';
        print_r($this);
    }
}

new Database();

这将输出

Database Object
(
    [DB_USER:Database:private] => foo
    [DB_PASS:Database:private] => foob
    [DB_DRIVER:Database:private] => foob_foob
)

<强> DEMO

修改

使用依赖注入:

$DB_USER = 'foo';
class Database
{
    private $DB_USER,
    $DB_PASS,
    $DB_DRIVER;
    public function __construct($dbUser){
        $this->DB_USER = $dbUser;
        $this->DB_PASS = 'foob';
        $this->DB_DRIVER = 'foob_foob';
        print_r($this);
    }
}

new Database($DB_USER);

<强> DEMO_2