andrew
andrew

Reputation: 5176

Php using one class in another class

I have a question about using my database class in other classes on my site. I only have need for one object of my database class and this is the instance that I want to run all my queries on.

I have a class called MysqliExtension which extends and adds some additional functionality to the mysqli class
I also have a class called Users which manages my users log ons/offs, fetches their info from the database etc. Finally, I have a file called config.php where I include these two classes and instantiate objects of the MysqliExtension and User classes.

config.php

require_once 'MysqliExtension.php';
require_once 'Users.php';

$database = new MysqliExtension(host,....);

I would like to get some opinions on the best way to pass my database object into my User object.

Option 1

In my config.php file

$user = new User($username,password);

in my Users.php file

    class User{


function myfunction(){

global $database;
$database->callDatabaseFunction();
return $some_result;
}

}

}

Option 2

In my config.php file

$user = new User($username,password,$database);

in my Users.php file

class User{

function __construct($username,$password,$database){    
$this->database = $database;
    }

function myfunction(){

$this->database->callDatabaseFunction();
return $some_result;
}

}

}

Which way is the best, or are they pretty much the same? Is there a different way all toghether that I haven't thought of?

Upvotes: 0

Views: 1132

Answers (2)

yoda
yoda

Reputation: 10981

If you only need one instance of a class : http://en.wikipedia.org/wiki/Singleton_pattern

Usage examples (using the PHP example in the refered link) :

$instance = Singleton::getInstance();

// or

Singleton::getInstance()->somefunction();

Note that this method only allows one instance of the object, so if you need to use more than one (let's say to have 2 connections to diferent databases), it's preferable not to use it.

Upvotes: 2

Chuck Callebs
Chuck Callebs

Reputation: 16431

I prefer the first way. It makes more sense to have the database logic completely separate from the user logic. However, if you make the functions public you can do something like this:

$user_results = database::callDatabaseFunction()

without having to instantiate the object.

Upvotes: 1

Related Questions