Reputation: 5525
I have database credential variables from a file, named config.php
:
$db_server = 'localhost';
$db_user = 'username';
$db_password = 'secret'
$db_name = 'dbname';
now, I have a PHP class under /class folder and it works perfectly fine for CRUD process. named MysqlCrud.class.php
:
class Database {
private $db_host = 'localhost'; // Change as required
private $db_user = 'username'; // Change as required
private $db_pass = 'secret'; // Change as required
private $db_name = 'dbname'; // Change as required
}
but, I want to use centralised variables from config.php
. that's why I add some lines like this :
include('../config.php');
class Database {
global $db_server;
global $db_user;
global $db_password;
global $db_name;
private $db_host = $db_server; // Change as required
private $db_user = $db_user; // Change as required
private $db_pass = $db_password; // Change as required
private $db_name = $db_name; // Change as required
}
but, I got this following error message :
Parse error: syntax error, unexpected 'global' (T_GLOBAL), expecting function (T_FUNCTION) in /home/*** on line **
why I can't use variables from config.php file inside Database class? what did I do wrong here? thank you.
Upvotes: 6
Views: 3141
Reputation: 14618
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
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.
Upvotes: 3
Reputation: 654
Here is an option to set your class members to a global value using __construct()
include('../config.php');
class Foo {
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
public function __construct() {
global $db_server;
global $db_user;
global $db_password;
global $db_name;
$this->db_host = &$db_server; // Change as required
$this->db_user = &$db_user; // Change as required
$this->db_pass = &$db_password; // Change as required
$this->db_name = &$db_name; // Change as required
}
}
Since we are using Assignment by Reference the inner class members are the same variables as the global ones (thus change as required).
Also if you want to avoid writing global
you can use the reserved variable $GLOBALS
, which as described in the documentation is:
An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.
So your code could became something like this:
$GLOBALS = array(
'DB_HOST' => 'localhost',
'DB_USER' => 'user',
'DB_PASS' => 'secret',
'DB_NAME' => 'my_db'
);
class Foo {
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
public function __construct() {
$this->db_host = &$GLOBALS['DB_HOST']; // Change as required
$this->db_user = &$GLOBALS['DB_USER']; // Change as required
$this->db_pass = &$GLOBALS['DB_PASS']; // Change as required
$this->db_name = &$GLOBALS['DB_NAME']; // Change as required
}
}
Upvotes: 1
Reputation: 9586
The problem with the approach you've chosen to use is that the class is no longer reusable. Any time you instantiate the Database
class, it will use the global variables.
I'd be more inclined to set it up like this:
Database.php
class Database {
private $host;
private $db_name;
private $username;
private $password;
function __construct($host, $db_name, $username, $password) {
$this->host = $host;
$this->db_name = $db_name;
$this->username = $username;
$this->password = $password;
}
}
Then in the file you use the Database
class:
include('../config.php');
$db = new Database($db_server, $db_name, $db_user, $db_password);
Upvotes: 4
Reputation: 41
Maybe you can try it like this:
function connDB()
{
$conn=mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
return $conn;
};
Put this function in your config file or another file such as globalFunctions.php (which contains every general function you need). Just call this function everytime you need it.
Upvotes: 4