view raw
Hanata Hanata - 6 months ago 45
PHP Question

How to access global varibale from inside class's function

I have file


require_once 'config.php';


$config = array('db'=>'abc','host'=>'',);

A class with name

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

Could some one tell me why it is null???
In, they told me that i can access but in reality is not .
I tried but have no idea.
I am using php 5.5.9.
Thanks in advance.


The variable $config in config.php is not global.

To make it a global variable, which i do NOT suggest you have to write the magic word global in front of it.

I would suggest you to read superglobal variables.

And a little bit of variable scopes.

What I would suggest is to make a class which handles you this.

That should look something like

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;