Jump to content

[SOLVED] Global variables or not? What's proper?


nloding

Recommended Posts

I posted this in the OOP section but decided to move it here because it deals with proper use of globals, just for this example it's within classes; and I wanted a quicker answer :) (I don't see many people in the OOP subforum ever).

 

I have several classes in individual include files.  As an example, we'll use my database class and my user class.  They do what their names imply.

 

In short, what is the most proper way to include the database object into the user object?  I've seen MANY ways of doing it, but I've also read it's not a good thing to use global objects like that.

 

Should I do this?

 

class Database {
  function Database {
    // connect to database
  }
}

$db = new Database;

class User {
  global $db;
  function User {
    // set $username or whatever
  }
}

... or ...

 

$db = new Database
$user = new User($db);

 

Or what?  I'm confused ...

 

I should also add that the database class is used in multiple classes in my page (an archive class, a forum class, a security class, and the user class).

To add another layer to this: how does this all fit together in the puzzle of multiple pages in a website?

 

What about having this at the top of every page: include('ultimate.inc')

 

ultimate.inc

<?php
include('database.inc');
include('user.inc');
$db = new Database;
$user = new User;
?>

<?php
include('database.inc');
include('user.inc');
$db = new Database;
$user = new User;
$user->db = $db;
?>

 

then in the user class....

 

<?php
$this->db->query;
?>

 

if you are using php5 9I stringly advise you do if - even if you don't do that much oop.

 

in php 5 you have the __autoload function which will auto include all teh files you need on a class call - have a look in the manual __autoload measn you only include those files you need and non that you don't ;)

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.