Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve "require_global"?

Tags:

php

Current situation:

  • I have the current version of my MVC Framework which uses classes as controllers.
  • I have some "vintage" modules from my old MVC Framework which uses simple, flat includes as controllers.

Much simplified that means:

New Version:

<?PHP
class blaController extends baseController {
    private $intVar;

    function dosomethingFunction() {
        $this->intVar = 123;
        $this->view('myView');
    }
}
?>

Old Version:

<?PHP
$globalVar = 123;
// view "controllername" is automatically shown
?>

I'm now trying to write a wrapper to be able to use my old controllers in my new MVC without having to rewrite everything. To do so, I have a "wrapper" controller:

class wrapController extends baseController {
    function dosomethingFunction() {
        require 'old_dosomething.function.php';
        $this->view('old_dosomething_view');
    }
}

(Once again: This is VERY, VERY simplified - just to get the idea over. Not actual code.)

The problem with that approach is, that the previously global variable $globalVar now only exists inside of the method "dosomethingFunction" and cannot be accessed by the view.

This wouldn't be the case if I could force the require to behave as "in global scope" so that $globalVar would once again be available in global scope.

So: Is there some way to achieve "require_global" or something similar?

(One solution for my problem would be to modify my old controllers to start with a bunch of "global" commands, but I'd prefer a solution where I don't have to change so much of that old code.)

(Note: Please don't tell me that GLOBALS are bad. It totally misses the point of this question. Just accept that it is a requirement to keep some old code working in a newer, cleaner environment.)

like image 965
BlaM Avatar asked Dec 17 '22 08:12

BlaM


1 Answers

You can add local variables defined within dosomethingFunction() to global scope:

class wrapController extends baseController {
    function dosomethingFunction() {
        require 'old_dosomething.function.php';
        //begin added code  
        $vararr = get_defined_vars();
        foreach($vararr as $varName => $varValue) 
              $GLOBALS[$varName] = $varValue;            
        //end added code          
        $this->view('old_dosomething_view');
    }
}

Note, that for this to work as expected, you should call require before using any other thing in the function. get_defined_vars() returns only variables from the current scope, so no array_diff hacks are needed.

like image 118
vartec Avatar answered Jan 02 '23 02:01

vartec