问题
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