简体   繁体   中英

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), eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM