I am trying to run index.php file with include("folder_1")
-- folder_1
| -- index.php
| -- other_stuff.php
In above mentioned directory structure. Normally to run index.php we'll write
include("folder_1/index.php")
.
expecting to run the index.php file with include("folder_1")
something like how import works in React.
Thanks :)
CodePudding user response:
There is no concept of "default file to include" in PHP. However, you can easily create a helper function to accomplish this. (Whether this makes sense or not, I leave for you to decide.)
function import(string $dir) {
include $dir . 'index.php';
}
Note that if your file to import contains variables, they will be "lost" in the function's scope. If your file only defines classes, functions, constants etc. that are scope-independent, this will work fine. (Refer to my original answer for importing variables from files using a helper function.)
Edit: It turns out OP wasn't asking about including multiple files. My original answer has been ported over to: How to include() all PHP files from a directory?.
CodePudding user response:
this is not how the include method works, for doing that you need to write your custom method, can use something like that
foreach(glob('includes/*.php') as $file) {
include($file);
}
CodePudding user response:
You can only scan directory and include each file. There is no native function.
Example:
function include_dir($path) {
$files = glob($path.'/*.php');
if(count($files) > 0) {
foreach($files as $file) {
include $file;
}
}
}
include_dir("./app");