problem in including all php files of a directory in php
I included all php files of a directory , an开发者_开发百科d it worked just fine
foreach (glob("directory/*.php") as $ScanAllFiles)
{
include_once($ScanAllFiles);
}
but problem is that the content of these files are all like this
$workers = array(
blah,
blah
);
$employers = array(
blah,
blah
);
now when i include all these files , its some how meaningless cause i will have repeated $workers and $employers
and i just want them to be like this
$workers = array()
$workers .=array()
now is there anyway to fetch $vars without editing all php files ?
You'll have to merge your arrays, by yourself, using for instance the array_merge()
function :
$all_workers = array();
foreach (glob("directory/*.php") as $ScanAllFiles) {
$workers = array(); // So if there is no $workers array in the current file,
// there will be no risk of merging anything twice
// => At worse, you'll merge an empty array (i.e. nothing) into $all_workers
include $ScanAllFiles;
$all_workers = array_merge($all_workers, $workers);
}
PHP will not do this automatically : basically, including a file is exactly like copy-pasting its entire content at the line you put your include
statement.
One option might be to include those files within a function so that you have scoped variables instead of globals.
$employees = array();
foreach (glob("directory/*.php") as $ScanAllFiles)
{
$employees = array_merge(my_include($ScanAllFiles), $employees);
}
function my_include($file) {
include_once($file);
return $employees;
}
In this case it might be best to rewrite the particular scripts. A not quite readable but functioning approach would be:
$workers = (array)$workers + array(
blah,
blah,
);
Albeit the +
approach is not always best, use array_merge
preferrably.
精彩评论