Mac Taylor
Mac Taylor

Reputation: 5148

problem in including all php files of a directory in php

I included all php files of a directory , and 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 ?

Upvotes: 0

Views: 103

Answers (3)

Micah Carrick
Micah Carrick

Reputation: 10187

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;
} 

Upvotes: 1

mario
mario

Reputation: 145482

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.

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 400992

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.

Upvotes: 4

Related Questions