views:

44

answers:

1

Hi there,

I am currently working on a php framework, which is in some cases structured like the ZendFramework. It has MVC etc. I did not found any equal matching to my problem.

My "problem" is I have a variable number of classes (models, controller), e.g. http_handler. Now I have that much classes I can not set them all manualy into variables.

Can I use $GLOBALS to set a $variableVar?

foreach($classes as $class)
{   
    include_once($class . '.php');
    $GLOBALS[$class] = new $class;
}

Does this create a new variable which will be accessable through the whole code? Example:

//... code
$http_handler->sendRequest($someArgs);
//... code
+3  A: 

It will, but you have to import the global variable in your method's scope:

function foo()
 {
  global $http_handler;

there are better solutions for this however. Check out the singleton pattern for example.

I asked a question about how to organize all these classes recently aside from using the singleton pattern, maybe some of the answers give you additional ideas: here

Pekka
daemonfire300
True, you have to assign a variable there as well, but a singleton approach still feels cleaner to me than working with globals and you can do exactly the same with a singleton as you can with a global object. Check out my question link, there are different solutions there that save assigning the variable - and a caveat that working this way is not really in the spirit of OOP, which is also important to note, no matter whether one lives by it or not.
Pekka