Leff7's avatar
Level 4

PHP - passing values to mysqli_connect

I have a legacy project, where I have a file with a class that in its construct method makes a connection with a database.

    public $mysqli;

    public function __construct(){
        $this->mysqli = mysqli_connect( "192.168.10.10", "homestead", "secret", "myDatabase" );
    }

For now, I would like to make this somewhat flexible and make a config file with an array of values that I would pass to mysqli_connect method. Something like this:

Config file:

    $mysqliConfig = [
      '192.168.10.10',
      'homestead',
      'secret',
      'myDatabase'
    ]; 

And then just require that in the other file and use it in the class constructor of that file:

    require_once 'includes/config.php';
    
    class Calculator{
    
        private $mysqli;
    
        public function __construct(){
            $this->mysqli = mysqli_connect($mysqliConfig);
        }

But that is not working, how should I do that?

0 likes
1 reply
tomopongrac's avatar
Level 51

Try

    require_once 'includes/config.php';
$calculator = new Calculator($mysqliConfig);
    
    class Calculator{
    
        private $mysqli;
    
        public function __construct($mysqliConfig){
            $this->mysqli = mysqli_connect($mysqliConfig);
        }

Please or to participate in this conversation.