1

I want to simplify files including or requiring process in PHP a little bit, so I wrote the function:

$files = array("filename", "other_filename");

function required_files($filenames) {
    foreach ($filenames as $filename) {
        require_once("admin/files/".$filename.".php");
    }
}

required_files($files);

It doesn't work unfortunately, but I know it's being processed by PHP, because whenever I change the "filename" to a name of the file, which doesn't exist, I got the error about that file is not existent. What am I doing wrong here?

PS: I tried to echo or return require_once() but no effect.

EDIT

That's within Wordpress template's functions.php.

Daniel
  • 538
  • 1
  • 8
  • 21
  • Because you're calling it in a function, variable scope rules apply – Mark Baker Apr 02 '17 at 11:06
  • But I'm passing variable into a function, which should be all right? The only problem is it's not benig retuned (I guess)? – Daniel Apr 02 '17 at 11:24
  • Any variables that are defined in the included files are limited to the scope of the required_files function – Mark Baker Apr 02 '17 at 12:23
  • So how to take them out of the required_files function scope then? Usually I use return or echo and it works but this time it doesn't. Shall I take the foreach loop out the function and get rid of the function itself? That would be the easiest way but I'd like to learn how to do that using the function. – Daniel Apr 02 '17 at 19:00

1 Answers1

1

It seems that what you want is not possible, at least not without declaring all the variables in the included files global (which is probably a bad idea).

While this question is not an exact duplicate, the answers to what (I think) is really being asked can be found on SO here and here.

If the project is object oriented, using an autoloader is a good alternative approach, but unviable of course if the code is written in procedural style.

Community
  • 1
  • 1
glaux
  • 701
  • 7
  • 20