<?php
class A {
public function qConnect($var1) {
$db_database = $var1;
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
}
}
?>
Below are the errors I receive when running File #1; I'm unable to make a connection in File #2. Any ideas?
The variables are not in scope in class A. You need to add global $db_hostname, $db_username, $db_password, $db_database; inside your function definition. So:
<?php
require_once 'login.php';
class A
{
public function qConnect($var1)
{
global $db_hostname, $db_username, $db_password, $db_database;
$db_database = $var1;
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
}
}
captainwillard, I'd like to pose another question to you. In Java, you can declare field attributes (instance variables). For example
public class foo {
public int myVariable = 200;
public void bar() {
System.out.print(myVariable); // outputs 200
}
}
In the example above you will be able to use (and reuse) the variable 'myVarialbe' for any method(s) within class foo.
If I understand correctly, in PHP you can declare a variable wherever you want, but then if you want to use it in a class with 10 functions you would have to re-declare your variable as global in each function within the class. For example
<?php
$zen = 55;
foo();
bar();
function foo() {
global $zen;
echo $zen;
}
function bar() {
global $zen;
echo $zen;
}
?>
Is there a better way to do this because it just seems redundant.
DO NOT use globals. This is entirely the wrong solution to your issue, and will only make things more difficult in the long run. Globals make code harder to understand, debug, maintain, and modify.
Instead, use Dependency Injection:
<?php
// define your connection details.
$db_hostname = "mysql hostname";
$db_username = "mysql username";
$db_password = "mysql password";
$db_database = '00044736';
// create your connection
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
// GIVE the connection to the object that needs it.
// this is Dependency Injection. That's all there is to it.
$myObj = new A( $connection );
// rest of your code
In your class A, you will assign the connection to a property, where it will be available to any class method which needs to use it.