Inside a class you can ONLY have member declaration. Global variables are NOT class members, therefore you can't have them inside the class. But you can have them inside methods.
class Database {
private $db_host;
//... the rest of them here
//class constructor. Gets called every time you create an instance of this class.
function __construct() {
global $db_server;
global $db_user;
global $db_password;
global $db_name;
$this->db_host = $db_server;
//.... you get the idea
}
}
Edit 2017-07-11:
Don't do this. Don't use global variables. They are easy to overwrite somewhere and you'd end up debugging a lot. Plus requiring the global keyword is dirty. A proper partial solution is provided by @br3nt. But it still uses global variables and initializes the $db variable in a global scope.
If you have access to the site config in Apache for example, for that website, you can use mod_env to set configuration in environment variables. Example:
<VirtualHost *:80>
.....
SetEnv DB_USER=myDatabaseUser
SetEnv DB_PASSWORD=12345
...
</VietualHost>
And then you can read this in PHP with getEnv('DB_USER') http://php.net/manual/en/function.getenv.php
Another option is to make your config return an array:
config.php
<?php
return [
'db_user'=>'myDbUser,
'db_password'=>'12345'
];
And you should have a single point of entry that ensures read-only access to that config.
Config.class.php
<?php
class Config {
private $_config;
public function __construct() {
$this->_config = include('path/to/config.php');
}
public function __get($key) {
if(isset($this->_config[$key])) {
return $this->_config[$key];
}
return null;
}
}
usage:
$config = new Config();
$dbUser = $config->db_user;
$dbPassword = $config->db_password;
Edit 2, same day
Why are globals bad?
Having global variables is nice because you can access them everywhere, right? Is it also a good practice to have all class members as public? No. Let's say you have a global variable used in many places. Someone accidentally writes this:
if($myGlobalVariable='something') { ... }
And his code works with just a weird bug that nobody cares about. But your code breaks because you actually depend on the exact value of $myGlobalVariable. And you look at the config, and see that it's the right value, and then scratch your head.
This is just one case. Unhindered read+write access to shared resources can be dangerous. It's easy to override, and no error will be output. It also pollutes the global space.
It's also a code smell if you have global functions in a config file. Think of config files as static text files that shouldn't even contain code. The only reason they're PHP files is because of speed, ease, and harder to break security that way.