Julius F
Julius F

Reputation: 3444

Creating variables using $GLOBALS

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

Upvotes: 1

Views: 143

Answers (1)

Pekka
Pekka

Reputation: 449405

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

Upvotes: 3

Related Questions