View Single Post
Old 09-29-2007, 04:08 AM   #1 (permalink)
jordie
The Wanderer
 
Join Date: Sep 2007
Location: Sydney, Australia
Posts: 19
Thanks: 0
jordie is on a distinguished road
Default I need your thoughts...

I work on an application that uses OOP heavily.

Because the classes are intermingled a lot (I'm trying to reduce this) they are stored in globals like:

PHP Code:
$GLOBALS['MY_CLASS_NAME'] = new classname(); 
However I came across another method that might be 'nicer'. Using static variables in a function. So the code would be like:

PHP Code:
function &GetClass($className){
    static 
$classes = array();
    if(isset(
$classes[$className])){
        return 
$classes[$className];
    }else{
        include_once(
BASE_PATH .'/includes/classes/class.'.strtolower($className).'.php');
        
$callClass $className;
        
$classes[$className] = new $callClass;
        return 
$classes[$className];
    }

Then the code from above would turn into:
PHP Code:
$objMyClass = &GetClass('classname'); 
Though its not global anymore, its in the static variable of the function, so I can still access it from withing another class or function. Example:
PHP Code:
function MyOtherFunction($objMyClass){
     
$objMyClass = &GetClass('classname');
     echo 
"My class says this: ".$objMyClass->ReturnSomething();

It looks a hell of a lot nicer than:
PHP Code:
function MyOtherFunction($objMyClass){
     echo 
"My class says this: ".$GLOBALS['MY_CLASS_NAME']->ReturnSomething();

I know some people might use:
PHP Code:
$objMyClass = new myclass();

function 
MyFunction(){
    global 
$objMyClass;
    echo 
"do something ".$objMyClass->DoSomething();  

But I can't do that from within another class though can I? Plus I don't like the idea of having those globals all over the place.... I'd rather just use $GLOBALS

But I guess when it comes down to it, I'm going to have to do some speed and memory tests and see which comes out on top. What does everyone else think about this though? Which is the 'better' method? Are there other methods that would be better? (Remember the instantiated classes need to be accessible anywhere)
jordie is offline  
Reply With Quote