如何使用自动加载来包含php文件?
这就是我现在在如何使用自动加载来包含php文件?,php,autoload,Php,Autoload,这就是我现在在index.php中包含文件的方式: <?php include('class.register.php');?> <!--additional files starts--> <?php include('register/register-form.php');?> <?php include('register/browse.php');?> <?php include('register/alldone.php');?
index.php
中包含文件的方式:
<?php include('class.register.php');?>
<!--additional files starts-->
<?php include('register/register-form.php');?>
<?php include('register/browse.php');?>
<?php include('register/alldone.php');?>
<?php include('search/browse.php');?>
<?php include('search/mobile-left-column.php');?>
<?php include('profile/mygloopal.php');?>
<?php include('profile/profile.php');?>
<?php include('profile/details.php');?>
<?php include('profile/posts.php');?>
<?php include('profile/create_post.php');?>
<?php include('profile/browse-search.php');?>
<?php include('profile/review.php');?>
<?php include('how.php');?>
<?php include('search/more-options.php');?>
但是它使用
classname
来定义页面。对于我上面的例子,不需要类来包含这些文件。我该怎么办呢?这个问题有点不清楚,所以我会按我的理解回答。如果标记为
的文件不是类,或者是类但没有命名,因此spl\u autoload\u register()
是一个选项,我通常会创建一个函数或类来自动包含文件。这里只是一个例子。它是不加选择的,这意味着它将加载文件夹中的所有内容,但您可以传递第二个参数,该参数是一个数组,专门告诉它要加载什么:
class AutoloadFiles
{
public function fInclude($dir = false)
{
// If the directory does not exist, just skip it
if(!is_dir($dir))
return $this;
// Scan the folder you want to include files from
$files = scandir($dir);
// If there are no files, just return
if(empty($files))
return false;
// Loop through the files found
foreach($files as $file) {
// Include the directory
$include = str_replace("//","/","{$dir}/{$file}");
// If the file is a php document, include it
if(is_file($include) && preg_match('/.*\.php$/',$include))
include_once($include);
}
// Return the method just so you can chain it.
return $this;
}
}
使用:
$iEngine = new AutoloadFiles();
$iEngine ->fInclude(__DIR__)
->fInclude(__DIR__.'/classes/')
->fInclude(__DIR__.'/functions/');
附加文件是类还是仅用于构建页面的文件?@Rasclatt,它们只是弹出框的文件正如您猜测的那样,如果它们不是类,那么该教程中的自动加载程序将不会对您有任何好处。使用扫描文件夹进行自动包含几乎是您所能做的一切。@Rasclatt是正确的,自动加载对类很有用,因为它的使用是因为
PHP
没有一种本机方法来导入在不同文件(如Java
或C
中定义的类。请问你为什么要自动加载这些文件?您是否需要为您拥有的大多数页面使用它们,并且需要为您需要的每个页面减轻加载它们的负担?
$iEngine = new AutoloadFiles();
$iEngine ->fInclude(__DIR__)
->fInclude(__DIR__.'/classes/')
->fInclude(__DIR__.'/functions/');