Autoload For Function in PHP

Hi there,
Recently, I am develop plugin for WordPress and I see I can call functions of WordPress everywhere like add_action, register_widget, … in my plugin forder… Now I am coding a website in pure PHP (do not use WordPress) How do I can create a function that can be called everywhere on mysite without using require_once, include_once like WordPress?

There is no autoload for the functions in PHP.

What you were using in wordpress is just regular functions which were stored in some file which was included using regular include operator. Not a hint of magic here.

So you can do exactly the same: store your functions in a file, then include it in a bootstrap script, and then call them everywhere.

1 Like

Can you give me an example? Thanks :grinning:

Just make sure the path and spelling are correct

<?php 
include 'myfunctions.php';
include 'more/functions.php';
....

Use composer and add your local packages as a new namespace in the composer.json file. Composer will handle all the autoloading for you. No need to go and reinvent a wheel.

I skimmed the below article and it looks like a good place to start if you’re not familiar with composer.

It seems you’re confusing functions with classes.

Well no I’m saying the op should be using classes rather than a mess of global functions. They should than load those class libraries using a well known dependency manager.

well, composer is able to “autoload” defined files that hold the function definitions.

Well, technically composer can be configured to automatically load selected files. It’s not really autoloading. Autoloading implies that functions are loaded when needed and not necessarily on every request.

oddz has the most performant approach. Wrap your functions in one or more classes. Of course it’s doubtful that the speed difference will even be noticed.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.