I’ve received Mixed responses on this depending what walk-through I read,
I’ve defined a class with 2 functions.
I want both functions to have access to the DB credentials
Currently, this code does not work unless I Copy and paste the variables into each function.
What am I doing wrong here?
<?php
class database {
function connect() {
var $username="my_username";
var $servername="localhost";
var $database="my_DB";
var $password="An_Awesome_Password";
var $con;
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
}
function disconnect() {
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
}
}
?>
This block:
Should come before the
function(), not inside it; but still inside theclassdefinition.And it’s good form to add an explicit visibility; private to start with:
Then, the functions refer to them as:
Ideally you will want to have those credentials to be passed in by the constructor:
Even more ideally, learn about PDO