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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵