0

I have 2 files index.php and env.php file. I would like to use the variable from env.php file inside the index.php file for connecting to the DB. I have tried doing this like this:

env.php:

<?php

$dbSettings = ["192.168.10.10", "homestead", "secret", "mydatabase"];

 ?>

And then requiring the env.file in index.php file and using the $dbSettings variable in index.php file like this:

<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );

require 'env.php';

class Calculator{

    var $mysqli;

    public function Calculator(){
        $this->mysqli = mysqli_connect( $dbSettings );

    }

But, I get the error:

Notice: Undefined variable: dbSettings in /home/vagrant/Projects/MyProject/index.php on line 14

Leff
  • 1,968
  • 24
  • 97
  • 201
  • [Variable scope](http://www.php.net/manual/en/language.variables.scope.php)... `$dbSettings` is defined in the global scope, but doesn't exist within the local scope of `Calculator::Calculator()` – Mark Baker Mar 29 '17 at 12:08
  • How can I make it accessible inside the local scope of the function Calculator of the class Calculator? – Leff Mar 29 '17 at 12:12
  • Inject it into the calculator constructor when you instantiate the calculator... I'm guessing that you've been reading some old PHP OOP tutorials from your use of `var` and the method name `Calculator`... suggest that you find some more modern tutorials for PHP5 or even 7 rather than old tutorials for PHP4 – Mark Baker Mar 29 '17 at 12:16
  • It is the script I have been given to work with, so need to fix it. But in the docs it says that I would be able to access the global variable if I add global keyword to it. I did that and I still get: ```Parse error: syntax error, unexpected 'global' (T_GLOBAL)``` – Leff Mar 29 '17 at 12:22
  • So where did you add the `global` in your code (really bad practise btw, use of globals isn't recommended) – Mark Baker Mar 29 '17 at 12:24
  • In the function Calculator: ```$this->mysqli = mysqli_connect( global $dbSettings );``` – Leff Mar 29 '17 at 12:25
  • Besides using `global` being bad; that's not how you use it.... the best option is still to pass it as a constructor argument – Mark Baker Mar 29 '17 at 13:12

0 Answers0