Hey guys,
I’m trying to use __construct() to connect, then __destruct() to disconnect from MySQL.
However when I try to, I get 2 errors:
Undefined variable: mysql in C:\wamp\www\kjv\classes\KJV.class.php on line 16
and
Fatal error: Call to a member function close() on a non-object in C:\wamp\www\kjv\classes\KJV.class.php on line 16Here is my class file code..
class KJV {
/* Database Variables */
private $host = "localhost";
private $dbuser = "username";
private $dbpass = "password";
private $dbname = "kjv";
function __construct() {
$mysql = new mysqli($this->host, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno()) { echo "Can't connect to MySQL Server. Error Code: " . die(mysqli_connect_error()); }
}
function __destruct() {
$mysql->close();
}
// End class
}
I’m sure I’m making some noob mistake, but I’m just learning OOP . 
Thanks in advance.
When you refer to a variable like you are there, you are referring to it “locally”. It is saying it is undefined because __construct() defines the variable $mysql, but once it leaves that function the variable $mysql is “garbage” as it was created within that function and not in the class.
You need to change it to a class member.
class KJV {
/* Database Variables */
private $host = "localhost";
private $dbuser = "username";
private $dbpass = "password";
private $dbname = "kjv";
private $mysql;
function __construct() {
$this->mysql = new mysqli($this->host, $this->dbuser, $this->dbpass, $this->dbname);
if (mysqli_connect_errno()) { echo "Can't connect to MySQL Server. Error Code: " . die(mysqli_connect_error()); }
}
function __destruct() {
$this->mysql->close();
}
// End class
}Awesome, it worked!
Thanks man.
I really like OOP , it is going to be a bit difficult to get used to but it’s very neat.
Just remember the difference between a “class level” variable and “local”.
class foo
{
var name;
function foo()
{
$this->name = 'Mickey';
}
function setName($name)
{
// different between the name variables.
$this->name = $name;
}
function printName()
{
print $this->name;
}
}
<\pre>