ProfK
ProfK

Reputation: 51094

Is it possible to write a replacement for 'require_once' etc. in PHP?

I have just written and tested my first non-hobby WordPress plugin, under Xampp on Windows 7, with PHP 5.3.8, and deployed it to my blog host, which is also a Windows environment, but I don't know what.

My first big surprise was nothing I could do to get relative paths working in require_once, so I have switched a few calls to use absolute paths - URL file access is disabled - but I want to wedge in an layer of abstraction here.

How could I wrap require_once to concentrate the decision on how to build the path into one location, e.g. a my_require_once that builds a path, then injects source from that path into the interpretation queue or whatever. Should I even be contemplating this?

I am aware that I can encapsulate the path determination into a function and use that function in the path parameter to require, but I would like to be able to 'undermine' existing require calls.

Upvotes: 0

Views: 1690

Answers (2)

a sad dude
a sad dude

Reputation: 2825

Unless you want to manipulate the relative paths in some more sophisticated way than just trying to prepend a number of absolute ones, set_include_path should be everything you need. Don't forget to append existing path though:

set_include_path(implode(PATH_SEPARATOR, $your_folders).PATH_SEPARATOR.get_include_path());

This has effect on all subsequent include/require/_once, but not any other file functions. You should also check that WordPress doesn't already do that, it might itself have a setting to set the path.

And answering to your question, no, it's not possible to override require_once. You can, however, use spl_autoload_register and avoid using require_once at all.

Upvotes: 1

CodeZombie
CodeZombie

Reputation: 5377

Define a base URL in a configuration file and append the relative path in the require_once statement:

require_once(BASE_URI . '/myfolder/myfile.php');

Upvotes: 2

Related Questions