2016-11-23 59 views
3

我有文件init.php如何從內部類的功能進入全球varibale

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

config.php

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

一個類名something.php

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

莫非有人告訴我爲什麼它是空的? 在php.net中,他們告訴我,我可以訪問,但實際上並不是。 我試過但不知道。 我使用PHP 5.5.9。 在此先感謝。

+1

你include'config.php'?只需包含並打印$ config –

+0

從全局變爲手動! –

回答

4

變量$configconfig.php不是全局的。

爲了讓它成爲一個全局變量,我不建議你必須在它的前面寫上魔術字global。我建議您閱讀superglobal variables

還有一點variable scopes

我會建議的是做一個類來處理你這個。

這應該是這個樣子

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; 
+0

omg!那麼'$ config'不會被認爲是全局變量?我認爲我require_once/include,那麼PHP會將其視爲全局變量。 – Hanata

1

包括像這樣的文件:

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

和打印數組var_dump($config);沒有必要的全球性的。

1

更改類有點傳遞構造函數的變量。

<?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(在一個地方,我們能夠避免他們)

2

使用Singleton模式這樣

<?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()); 
+0

不錯!謝謝。我沒有想到辛格爾頓模式。謝謝你的建議。 – Hanata