Class Scope
Posted: Sun Jul 09, 2006 7:53 pm
How do I access and call functions in a database class that I wrote from within a login class that I wrote?
A community of PHP developers offering assistance, advice, discussion, and friendship.
http://forums.devnetwork.net/
Code: Select all
class login
{
var $dbInstance;
function login()
{
$this->dbInstance =& new Database();
}
function foo()
{
$this->dbInstance->method(); // note: I don't remember if this works as expected in php 4 or not, but it does in 5. If it doesn't, make a reference to the database instance first, then go through that.
}
function foo2($dbInstance)
{
$dbInstance->method();
}
}Code: Select all
$Database = new databaseConnection();
$Database->connect($host, $username, $password);
$Database->selectDatabase($database);
$Login = new login;Code: Select all
class login {
function login() {
$this->method = "POST";
$this->action = "#";
$this->name = "LoginForm";
$this->template = "includes/templates/login.php";
$this->username = '';
if ((isset($_POST['action'])) and ($_POST['action'] == 'Login')) {
$this->validate();
}
}
function validate() {
if ((!isset($_POST['username'])) or ($_POST['username'] == '')) {
$SystemStatus[] = 'Please enter your username.';
return false;
}
if ((!isset($_POST['password'])) or ($_POST['password'] == '')) {
$SystemStatus[] = 'Please enter your password.';
return false;
}
$Database->table = 'members';
$Database->parameters = array('username' => $_POST['username']);
$Database->limit = '1';
$Database->dispatch('select', 'user_status user_password');
if ($Database->getNumRows() == 1) {
} else {
$SystemStatus[] = "Your username could not be found in the database.";
}
}
function display() {
include $this->template;
}
}
class databaseConnection {
function databaseConnection() {
$this->database = '';
$this->query = '';
$this->fields = '';
$this->table = '';
$this->parameters = '';
$this->limit = '';
$this->orderby = '';
$this->joins = '';
$this->linkid = '';
$this->connected = false;
$this->dbselected = false;
}
// etc. etc..
}Code: Select all
<?
class Foo
{
private $db;
public function __construct ($obj)
{
$this->db = $obj;
}
}
class Bar
{}
$foo = new Foo(new Bar);
?>Code: Select all
$GLOBALS['Database']Yeah, reading through the manual I started using __construct as well. I cannot re-instantiate the database class though as it's only initialized once per page because I want it to operate that way.Jenk wrote:I use the constructor to create the instances for the DB object
Code: Select all
// instantiate an independant database object
$dbObject= new DB();
// pass to the Foo object instance for use
$newFoo= new Foo($dbObject);
// another object requires database access
$newBar= new Bar($dbObject);