Рефакторинг require_once-файла в проекте

Я новичок в PHP. И я работаю над проектом с этой иерархией каталогов: model , элементы control , view и helper папки находятся в моей папке проекта

Теперь я пытаюсь написать файл init.php и require_once в каждом из файлов control и model , вот мой init.php

 <?php $current_dir = basename(getcwd()); $model_dir = "model"; $helper_dir = "helper"; function require_helper(){ $handle = opendir("../{$helper_dir}"); while($file = readdir($handle)){ if($file != "." && $file != ".."){ require_once "../{$helper_dir}/{$file}"; } } } if($current_dir == "control"){ $handle = opendir("../{$model_dir}"); while($file = readdir($handle)){ if($file != "." && $file != ".."){ require_once "../{$model_dir}/{$file}"; } } require_helper(); } elseif( $current_dir == "model") { $handle = opendir($current_dir); while($file = readdir($handle)){ if($file != "." && $file != ".."){ require_once "{$file}"; } } require_helper(); } ?> 

Но когда я тестирую свой проект, я получаю эту ошибку:

Примечание. Неопределенная переменная: сеанс в C: \ wamp \ www \ harmony \ control \ login.php в строке 11

Вот мой файл login.php :

     <?php require_once "../helper/init.php"; ?> <?php if(isset($_GET["logout"]) && $_GET["logout"] == "true" ){ $session->logout(); } if($session->is_logged_in()){ redirect_to("../view/index.php"); } if(isset($_POST["submit"])){ $username = $db->escape_value($_POST["username"]); $password = $db->escape_value($_POST["password"]); $password = hash('sha1' , $password); $arr = User::auth($username , $password); if($arr){ $usr = $db->instantiate($arr); $session->login($usr); } else { Session::notify("Invalid login information."); } } ?> из <?php require_once "../helper/init.php"; ?> <?php if(isset($_GET["logout"]) && $_GET["logout"] == "true" ){ $session->logout(); } if($session->is_logged_in()){ redirect_to("../view/index.php"); } if(isset($_POST["submit"])){ $username = $db->escape_value($_POST["username"]); $password = $db->escape_value($_POST["password"]); $password = hash('sha1' , $password); $arr = User::auth($username , $password); if($arr){ $usr = $db->instantiate($arr); $session->login($usr); } else { Session::notify("Invalid login information."); } } ?> 

    Так вы могли бы мне помочь? что случилось?

    Related of "Рефакторинг require_once-файла в проекте"

    Вы пытаетесь получить доступ к $ current_dir, $ model_dir и $ helper_dir внутри функций. Вы не можете обращаться к переменным, которые были объявлены вне функции, если они не объявлены глобальными или фактически не передаются в функцию.

    так например:

     function require_helper(){ global $helper_dir;//this is key $handle = opendir("../{$helper_dir}"); while($file = readdir($handle)){ if($file != "." && $file != ".."){ require_once "../{$helper_dir}/{$file}"; } } }