Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I define properties for a class in php?

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);
                        }
            }
?>
like image 436
Dan O'Boyle Avatar asked Jun 14 '12 13:06

Dan O'Boyle


1 Answers

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

like image 60
Ja͢ck Avatar answered Oct 20 '22 22:10

Ja͢ck