I'm having problem with global variable in PHP. I have mysqli config file which contains only following data:
$mysqli = new mysqli("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
I have the following class on another file:
class user{
function username_exists($username){
global $mysqli;
if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?")) {
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
$count=$stmt->num_rows;
$stmt->close();
}
return ($count > 0 ? true : false);
}
...
some more functions
...
}
Now this works fine, but in my previous question on SO, i was told that it is a bad practice to access global variable like I'm doing in above class. So, I'm trying to pass the global variable in the constructor, in following way:
private $mysqli;
function __construct()
{
global $mysqli;
$this->mysqli = $mysqli;
}
function username_exists($username){
//global $mysqli;
if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {
And I get the following error:
Fatal error: Call to a member function prepare() on a non-object in...(line number)
Can you please tell me whats problem with it and how this can be fixed? Thanks. Edit: Sorry for the spelling mistake of __construct. It was only mistake typing here, and the error isnt because of that.