user3518302
user3518302

Reputation: 1

How to access the config php values (multidimensional array) to class function in PHP

I need to get the values from config.php for PHP class function. I am new to php so i am facing issue to assign it global variable and use it in class functions.

config.php is having the below return statement

return [
    'database' => [
        'host' => 'localhost',
        'name' => 'somedb',
        'user' => 'someuser',
        'pass' => 'somepass'
    ],
    'api => [
        'url'=>'apiurl' 
       ]
];

I am trying the below implementation;

$loadvalues=include_once('config.php');

global url;

url=$loadvalues['api']['url']

Class APILoader{

    function getAccess(){

        //url from config need to be used here
    }

}

Upvotes: 0

Views: 152

Answers (1)

slepic
slepic

Reputation: 641

You need to import the global variable in every scope you wanna use it. You do it with they global keyword.

function getAccess(){
    global $url;
    //whatever now...
}

But you better avoid using global variables. You can inject whatver value you want to the constructor of the class, store it in the class property and use it when needed.

$loadvalues=include_once('config.php');


Class APILoader{
    private $url;
    public function __construct($url) {
        $this->url = $url;
    }
    function getAccess(){

        //use $this->url here
    }

}

new APILoader($loadvalues['api']['url']);

Upvotes: 1

Related Questions