I’m trying to work on project using a proprietary mvc and we have a file called global.php which has code similar to this in it…
<?php
session_start();
require('config/config.php');
require('classes/pdo_extender.php');
require('classes/mainClass.php');
require('classes/utilities.php');
$mainClass = new mainClass;
?>
Then we have a page in the root directory that has the following code
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/globals/global.php');
$mainClass->init();
?>
The code in the init function just includes a file based on the name of the current viewed page…
public function init() {
$section=explode("/",$_SERVER['SCRIPT_NAME']);
$section=explode(".",$section[count($section)-1]);
include("controllers/".$section[0].".php");
}
So say we have in the root login.php, it includes global.php and calls the init function with out me having to redeclare $mainClass, so it then includes controllers/login.php but on this page now I have to redeclare $mainClass = new mainClass;
Is there anyway to get it so the files included from the init function still have access to the initial $mainClass set in global.php?
EDIT: Another solution I found in addition to the accepted is as follows:
public function init() {
$section=explode("/",$_SERVER['SCRIPT_NAME']);
$section=explode(".",$section[count($section)-1]);
$mainClass= $this;
include("controllers/".$section[0].".php");
}
I had something like this come up once before. The issue right now is that the files included within that function inherit the function’s scope so they will not be accessible globally as you would like. A possible solution would be to use te function to determine the file names and paths and then returning them in an array of sorts or a string if it’s only one. Then doing the include outside of the function globally.