Php 重构需要在项目中使用一次文件
我是PHP的初学者。我正在使用这个目录层次结构处理项目:Php 重构需要在项目中使用一次文件,php,refactoring,undefined,require-once,Php,Refactoring,Undefined,Require Once,我是PHP的初学者。我正在使用这个目录层次结构处理项目:model、control、view和helper文件夹都在我的项目文件夹中 现在我正试图在control和model文件中编写一个文件init.php和require\u一次它,下面是我的init.php <?php $current_dir = basename(getcwd()); $model_dir = "model"; $helper_dir = "helper"; function r
model
、control
、view
和helper
文件夹都在我的项目文件夹中
现在我正试图在control
和model
文件中编写一个文件init.php
和require\u一次
它,下面是我的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();
}
?>
你能帮帮我吗?发生了什么问题?您试图访问函数内部的$current\u dir、$model\u dir和$helper\u 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}";
}
}
}
如果(isset($session)&&$session->is\u logged\u in()),请尝试添加{到那种情况。这应该会消除错误。在所有文件中重新加载
init.php
?你做错了!查找front controller
design。基本上你应该有一个文件来处理所有请求并加载必要的文件。这大大减少了重复的样板代码量。@Mchl你能为我提供关于前端控制器设计有一个很好的php教程吗?谢谢:)不太好。我还没有写一个;P不过我的想法是让你的index.php
根据URL参数决定需要和执行哪些文件/类(进入$\u GET
数组。我研究的所有PHP MVC框架都使用此方案的变体。哦,这样我就可以修改init.PHP
,这样我就可以使用$\u GET variable?或者只需重新开始。
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}";
}
}
}