Reputation: 3661
Let's say, we have index page that includes php/common.php
.
foreach (glob("functions/*.php") as $filename)
{
include $filename;
}
Code above located in common.php
. So index.php
includes common.php
and common must include all files from functions
folder which located in the same folder with common.php
When I try to call some function (which located in one of php/functions
folder's files) from index.php
getting error message Call to undefined function
. Used the code below instead (to test if there is any problem with foreach loop)
include "functions/ipdetect.php";
Got result. So why foreach doesn't work in my case? Maybe php fires foreach AFTER inluding the common.php
into index.php
?
Upvotes: 2
Views: 4123
Reputation: 4419
For starters you should use include_once
it stops you from including things twice resulting in more errors, and the minor overhead does very little.
foreach (glob("functions/*.php") as $filename)
{
include_once $filename;
}
Is the "functions" folder under the root or under the "php" folder that common is in? If under php you'll need this change:
foreach (glob("php/functions/*.php") as $filename)
{
include_once $filename;
}
Edit removed incorrect explaination - read darren cooks comments:
@DEVastor The direct include works because it was your glob() that wasn't working, not your include().
Upvotes: 2
Reputation: 28913
Works for me (see below code - these are the full files). Running "php index.php" from command line outputs "Hello World!". Hint: put some global code in one of the files being included (see a.php below; uncomment the echo). That should tell you if the file is being included. BTW, as others have said, always use include_once unless you have a good reason not to.
--- index.php ----
<?php
include "common.php";
echo f()."\n";
?>
--- common.php ---
<?php
foreach (glob("functions/*.php") as $filename)
{
include $filename;
}
?>
--- functions/a.php ---
<?php
//echo "*** In a.php ***\n";
function f(){
return "Hello World!";
}
?>
Upvotes: 2