Refactoring require_once file in a project

我怕爱的太早我们不能终老 提交于 2019-12-25 03:15:38

问题


I'm a beginner in PHP. And i'm working on project with this directories hierarchy : model, control, view and helper folders are in my project folder

Now i'm trying to write a file init.php and require_once it in each of control and model files, here's my 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();
    } 
?>

But when i test my project i get this error :

Notice: Undefined variable: session in C:\wamp\www\harmony\control\login.php on line 11

Here's my login.php file :

<?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.");
        }
    }    

?>

So could you help me please ? what's wrong is going on ?


回答1:


You're trying to access $current_dir, $model_dir and $helper_dir inside of functions. You can't access variables which were declared outside of a function unless they are declared global, or else actually passed into the function.

so for example:

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}";
        }
    }
}


来源:https://stackoverflow.com/questions/6884815/refactoring-require-once-file-in-a-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!