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.

4
  • Because you're calling it in a function, variable scope rules apply Commented Apr 2, 2017 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)? Commented Apr 2, 2017 at 11:24
  • Any variables that are defined in the included files are limited to the scope of the required_files function Commented Apr 2, 2017 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. Commented Apr 2, 2017 at 19:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.