Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Variable From Other File To Be Used Inside PHP Class

Tags:

php

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.

like image 637
Saint Robson Avatar asked Dec 24 '22 10:12

Saint Robson


2 Answers

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);
like image 161
br3nt Avatar answered Dec 28 '22 09:12

br3nt


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.

like image 43
Valhala Avatar answered Dec 28 '22 09:12

Valhala