ano*_*mox 8 php .htaccess class include autoload
我有这个自动加载代码:
function __autoload($class_name)
{
//class directories
$directorys = array(
'./Controls/',
'./Config/',
'./Utility/'
);
//for each directory
foreach($directorys as $directory)
{
//see if the file exsists
if(file_exists($directory.$class_name . '.php'))
{
require_once($directory.$class_name . '.php');
//only require the class once, so quit after to save effort (if you got more, then name them something else
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我有三个目录,他们持有我所有的类和函数.
我可以在Controls目录中创建一个自动加载文件,并使用它来加载其他php文件中的所有函数或类,我的意思是例如index.php文件/portal/main/index.php
是有可能加载是类controls和config在index.php文件,而不包括在上述的任意文件index.php的文件
我的意思是自动加载会自动了解哪个文件正在请求类或函数,并为其包含该文件.
更新的代码:
function __autoload($class_name)
{
//class directories
$directorys = array(
'/Controls/',
'/Config/',
'/Utility/'
);
//for each directory
$ds = "/"; //Directory Seperator
$dir = dirname(__DIR__); //Get Current file path
$windir = "\\"; //Windows Directory Seperator
$path = str_replace($windir, $ds, $dir);
foreach($directorys as $directory)
{
//see if the file exsists
if(file_exists( $path . $directory . $class_name . '.php'))
{
require_once( $path . $directory . $class_name . '.php');
//only require the class once, so quit after to save effort (if you got more, then name them something else
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我已经更新了代码并且它包含了文件,但我唯一的问题是这个函数没有自动运行,
例如我的自动加载文件在:root/Controls/autoload.php
我需要一些类和函数:root/portal/index.php
当我在index.php中定义类时,我得到文件不存在的错误,我应该手动调用autoload.php文件index.php
我如何使自动加载智能,我不应该包含在每个文件包括类?
请帮帮我.提前致谢
你的程序和你一样聪明.如果你梦想解决超出主流语言能力的问题,问题就在于你的梦想,而不是语言.
要自动加载PHP代码,请auto_prepend_file在php.ini中设置自动加载器脚本.或者,您可以将其作为集中入口点并使用mod_rewirte指示流量.
这是不好的做法.这两种方法都依赖于服务器配置,例如.htaccess,并不总是可用.您也可以覆盖现有的配置或无法重写某些路径.
您应该在每个入口点手动集中PHP请求(并封锁非入口点)或require_once.
查看Wikipedia,Magento或WordPress.它们拥有数百甚至数千个全局函数.
您可以在PHP中动态定义任何内容.除非它真正运行代码,否则PHP永远不会确信会得到什么.自动加载器只是将文件名信任为正确且完整的文件内容声明.
由于您的自动加载器会扫描所有文件夹,因此您可能希望在首次运行时生成静态文件映射,并使用映射进行子序列加载.当然,假设你不打算用PHP动态创建类文件.
简单的手动解决方案:将您的autoload文件放在项目根目录中并将其包含在索引文件中,这将完成工作.
但是如果你想使用htaccess或php.ini:将一个调用的文件.user.ini放入文档根目录并在其中添加auto_prepend_file指令:
auto_prepend_file = /home/user/domain.com/init.php
Run Code Online (Sandbox Code Playgroud)
该文件必须位于PHP的include_path中.因此,您必须将文件的目录设置为php.ini中的include_path,或者使用php_value语句在.htaccess中执行.
php_value include_path ".:/path/to/file_directory"
php_value auto_prepend_file "file.php
Run Code Online (Sandbox Code Playgroud)
如果你在.htaccess中使用上面的方法,请务必从php.ini中复制include_path并添加:/path_to/file_directory所以你不会丢失任何已经需要的包含.
或者,只需添加:/path/to/file_directory to include_path directly in the php.ini
更新
如果无法修改include_path,则可以尝试指定auto_prepend_file的相对路径.这应该有效,因为发送的文件路径的处理方式与使用require()调用的方式完全相同:
php_value auto_prepend_file "./file.php"
Run Code Online (Sandbox Code Playgroud)