I just started doing OOP, so I apologize in advance if there is a simple solution.
Basically I need to use my $mysqli object inside a class. I’ve seperated it into two files.
config2.php
class Config
{
public $host = 'localhost';
public $username = '****';
public $password = '****';
public $database = '****';
function report_error($query)
{
$email = '*@hotmail.com';
$subject = 'MySQL error.';
$message = "IP: {$_SERVER['REMOTE_ADDR']} \n URL: http://{$_SERVER['SERVER_NAME']}{$_SERVER['REQUEST_URI']} \n\n MySQL query: {$query} \n\n MySQL error: " . $mysqli->error();
mail($email, $subject, $message);
die('Oops, an error has occured. The administrator has been notified.');
}
}
$config = new Config();
$mysqli = new mysqli($config->host, $config->username, $config->password, $config->database);
if($mysqli->connect_error)
report_error($mysqli);
administration.php
require('includes/config2.php');
$mysqli->real_escape_string(); // Works out of scope.
class Account
{
public $username = $mysqli->real_escape_string(); // Doesn't work in scope.
public $password;
function login()
{
}
}
Thanks for the help guys, I appreciate it :).
You should pass the object to the constructor of
Accountand save it as a private instance variable.Accountis directly dependent on an instance ofmysqli, so there is nothing wrong with making that clear by specifying it as a required parameter in the constructor. That is the only way you can make sure that wheneverAccountis used the mysqli object is there too. If you access it from a global state instead (by either having a static accessor or by directly accessing the global scope) you can never guarantee that it is really there.