如何使用自动加载包含PHP文件?

时间:2016-02-07 05:25:48

标签: 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');?>
<?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');?>

我指的是本教程,用名称空间学习autoload

http://www.zainabed.com/2014/11/php-tutorials-autoload-php-classes.html

但它使用classname来定义页面。对于我的上述情况,不需要包含文件的类。我该怎么办呢?

1 个答案:

答案 0 :(得分:0)

问题有点不清楚,所以我会按照我的理解回答它。如果您标记为Image的文件不是类,或者是类但未命名,<!--additional files starts-->是一个选项,我通常会创建一个函数或类来自动包含文件。这只是一个例子。它是不分青红皂白的,这意味着它会加载文件夹中的所有内容,但你可以传递第二个参数,这个参数是一个数组,告诉它具体加载什么:

spl_autoload_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;
            }
    }