如何从 class 的函数内部访问全局变量

How to access global variable from inside class's function

我有文件 init.php:

<?php 
     require_once 'config.php';
     init::load();
?>

config.php:

<?php 
     $config = array('db'=>'abc','host'=>'xxx.xxx.xxx.xxxx',);
?>

名称为 something.php 的 class:

<?php
     class something{
           public function __contruct(){}
           public function doIt(){
                  global $config;
                  var_dump($config); // NULL  
           }
     } 
?>

为什么为空?
在 php.net,他们告诉我可以访问但实际上不能访问。 我试过但不知道。 我正在使用 php 5.5.9.

像这样包含文件:

 include("config.php"); 
     class something{ ..

并将数组打印为 var_dump($config); 不需要全局。

config.php 中的变量 $config 不是全局变量。

为了使它成为一个全局变量,我不建议你必须在它前面写魔术词global

我建议您阅读 superglobal variables

还有一点 variable scopes

我建议做一个 class 来处理这个。

应该类似于

class Config
{
    static $config = array ('something' => 1);

    static function get($name, $default = null)
    {
        if (isset (self::$config[$name])) {
            return self::$config[$name];
        } else {
            return $default;
        }
    }
}

Config::get('something'); // returns 1;

稍微更改 class 以在构造函数上传递变量。

<?php
     class something{
           private $config;
           public function __contruct($config){
               $this->config = $config;
           }
           public function doIt(){
                  var_dump($this->config); // NULL  
           }
     } 
?>

那么,如果你

  1. 包括config.php
  2. 包括yourClassFile.php

然后做,

<?php
$my_class = new something($config);
$my_class->doIt();
?>

应该可以。

注意:最好不要使用Globals(在我们可以避开它们的地方)

像这样使用单例模式

<?php
     class Configs {
        protected static $_instance; 
        private $configs =[];
        private function __construct() {        
        }

        public static function getInstance() {
            if (self::$_instance === null) {
                self::$_instance = new self;   
            }
            return self::$_instance;
        }

        private function __clone() {
        }

        private function __wakeup() {
        }     
        public function setConfigs($configs){
         $this->configs = $configs;
        }
        public function getConfigs(){
         return $this->configs;
        }
    }

Configs::getInstance()->setConfigs(['db'=>'abc','host'=>'xxx.xxx.xxx.xxxx']);

     class Something{
           public function __contruct(){}
           public function doIt(){
                  return Configs::getInstance()->getConfigs();
           }
     } 
var_dump((new Something)->doIt());