0

I have saw this answer about require multiple php files, I want to do it use class,like this

class Core
{
    function loadClass($files)
    {
        $this->files = func_get_args();
        foreach($files as $file) {
            require dirname(__FILE__)."/source/class/$file";
        }
    }
}

But when I use

$load = new Core;
$load->loadClass('class_template.php');

it doesn't work, can anyone help me to find the error ?

carry0987
  • 117
  • 1
  • 2
  • 14
  • 1
    because you are reading `$files` as array and sending it as a string. just add one new line under loadClass file. `if(!is_array($files)){ $files = array($files)}` or when you are calling your files pass it in array like. `$load->loadClass(['class_template.php'])` – Ashish Patel Apr 07 '18 at 05:07
  • I would recommend looking into `PSR0` or `PSR4` auto loading of classes. – ArtisticPhoenix Apr 07 '18 at 05:10
  • 1
    @AshishPatel thanks,now I know how different array between class and pure function – carry0987 Apr 07 '18 at 05:28
  • @ArtisticPhoenix I know that,but I just want to require 5 or 6 class files,so I decide make an require function file – carry0987 Apr 07 '18 at 05:29

1 Answers1

1

You should pass $this->files to foreach. $files is a local variable and a string. $this->files is a instance variable and an array.

class Core {
    function loadClass() { // there is no need for `$files` here
        $this->files = func_get_args();
        foreach($this->files as $file) { // $this->files not $files
            require dirname(__FILE__)."/source/class/$file";
        }
    }
}

$load = new Core;
$load->loadClass('class_template.php');
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67