How Do I define properties for a class in php?
This block:
var $username="my_username";var $servername="localhost";var $database="my_DB";var $password="An_Awesome_Password";var $con;
Should come before the function()
, not inside it; but still inside the class
definition.
And it's good form to add an explicit visibility; private to start with:
class database { private $username="my_username"; private $servername="localhost"; // etc. etc.
Then, the functions refer to them as:
$this->username;$this->con;etc.
Ideally you will want to have those credentials to be passed in by the constructor:
private $servername;private $database;private $username;private $password;private $con;function __construct($host, $user, $password, $dbname){ $this->servername = $host; $this->username = $user; $this->password = $password; $this->database = $dbname;}
Even more ideally, learn about PDO
To access object property you need to use $this->property_name
$this->con = mysql_connect($this->servername,$this->username,$this->password);
Class code would go like this:
<?phpclass database { var $username="my_username"; var $servername="localhost"; var $database="my_DB"; var $password="An_Awesome_Password"; var $con; function connect() { $this->con = mysql_connect($this->servername,$this->username,$this->password); if (!$this->con) { die('Could not connect: ' . mysql_error()); } } function disconnect() { $this->con = mysql_connect($this->servername,$this->username,$this->password); if (!$this->con) { die('Could not connect: ' . mysql_error()); } mysql_close($this->con); }}?>