我有这个自动加载器方法,用于根据需要包含类文件。
public static function autoloader($className) {
$fileExists = false;
foreach(array(LIBS_PATH, CONTROLLERS_PATH, MODELS_PATH) as $path) {
// Check if the class file exists and is readable
if(is_readable($classPath = $path . '/' . $className . '.php')) {
// Include the file
require($classPath);
$fileExists = true;
break;
}
}
if($fileExists === false) {
exit('The application cannot continue as it is not able to locate a required class.');
}
}
这很好,但我想这样更好:
public static function autoloader($className) {
foreach(array(LIBS_PATH, CONTROLLERS_PATH, MODELS_PATH) as $path) {
// Check if the class file exists and is readable
if(is_readable($classPath = $path . '/' . $className . '.php')) {
// Include the file
require($classPath);
return;
}
}
exit('The application cannot continue as it is not able to locate a required class.');
}
如您所见,我在循环中间使用 return 语句来终止函数的其余部分,因为已包含类文件并且该方法已完成其工作。
如果找到匹配项,哪种方式是跳出循环的最佳方式?我只是不确定是否使用 return 语句,因为我总是将它与从方法返回一些值相关联。