0

Without using include_once or any include/require how can I reference functions declared in other php files in the current directory? Just like we use fopen.

Including contents of php files which contain code not in functions can be a clutter. It'd be better if function usage is linked automatically to its definition.

I've also checked How to include() all PHP files from a directory? which requires some code to do it.

I'm not able to find answer of this anywhere in internet may be because of too common search terms for this problem.

Community
  • 1
  • 1
user774250
  • 161
  • 2
  • 14

3 Answers3

3

The most logical approach would be to use OOP and autoloading.

That way you would only load the classes that you actually use.

Otherwise the accepted answer from the question you linked to, is the way to go.

jeroen
  • 91,079
  • 21
  • 114
  • 132
1

You can use glob to traverse the directory and then include them:

$phpfiles = glob('mydir/*.php');
foreach($phpfiles as $file)
  do_something_with_the_file($file) // why not include_once $file ?

As you are referencing functions in other files, you cannot use the autoloader because the autoloader operates on classes. Autoloading classes would be a much better solution.

JvdBerg
  • 21,777
  • 8
  • 38
  • 55
0

If you're keen on using classes and OO vs Procedural, this will include a file by the same name as the class that's being called, and will not include class files in the directory that are not needed.

Called from the root directory of the site/application.

define( "APP_PATH", dirname( __FILE__ ) ."/" );

function my_autoloader($class)
{
    include 'core/classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');

Assuming you keep all your classes in a similar directory structure:

site/core/classes

You get the idea.

jdstankosky
  • 657
  • 3
  • 15