1

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
Julius F
  • 3,434
  • 4
  • 29
  • 44

1 Answers1

3

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

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Alright, thank you very much. ..but the singleton pattern still requires a variable to be assigned to ;) I currently have some "main"objects containing singleton/factory instances of the "sub"objects of my framework. $main->controllers->SpecificController->Method() $main->model->User->SpecificModel->Method() If I have a controller/model this huge syntax is wrapped to a simple one, also for security reasion: $user = &$main->model->User – Julius F Dec 05 '09 at 14:41
  • 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 Dec 05 '09 at 14:49