Hanata Hanata - 11 days ago 6
PHP Question

How to access global varibale from inside class's function

I have file

init.php
:

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


with
config.php
:

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


A class with name
something.php
:

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


Could some one tell me why it is null???
In php.net, 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.

Answer

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;
Comments