Reputation: 1664
I know this may sound a little odd, but is it possible to create a superclass or global class which can be called from any page/class without the need to include/use?
I want to have an activity tracker and a custom error log on my site that records the activities and errors from the users but i pretty much need them on every page and every class. Rather than having to import them all the item, can you create one that is always available? Such as the core classes for PHP? (mysql_, ftp_, include_*, etc)
Thanks!
Upvotes: 1
Views: 787
Reputation: 12806
Not without digging into the source code or adding modules (or using auto_prepend_file as mentioned by mario). You can, however, use the autoloader to automatically include class files when needed. This is the code I use (which makes use of namespaces):
// Autoload any classes
spl_autoload_register(function ($class)
{
// Throw an exception if the file does not exist or cannot be included
if (!is_file($file = APPLICATION . ltrim(str_replace('\\', '/', $class), '/') . '.php') || !include $file)
{
throw new Exception(PAGE_NOT_FOUND);
}
}
);
So let's say I have a class called (with the namespace) \Models\EmailAddressValidator
I save it in /application/Models/EmailAddressValidator.php
and when I try to call it the autoloader automatically includes that file.
Upvotes: 0
Reputation: 38446
If you're okay with including at least a single file, you could put an autoloader into an include and have that handle all of your loading for you. You can read in more detail about spl_autoload_register
here.
From the documentation, a sample setup could be:
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
This code would go into your file that's included on every page. With it, you'll be able to do the following without ever manually including the class file:
$superClass = new SuperClass();
Now, doing this assumes you have a file located at classes/SuperClass.class.php
and it does, in fact, contain a class SuperClass {
declaration (not required, but you'll get an error if it doesn't).
You can always change the path defined in your autoloader function, as well as the file-naming schema. Also, you can use several different locations/logic or whatever is needed to suit your setup.
For instance:
function adv_autoloader($class) {
if (file_exists('classes/' . $class . '.class.php') {
require('classes/' . $class . '.class.php');
} else if (file_exists('includes/' . $class . '.inc.php') {
require('includes/' . $class . '.inc.php');
} else {
// can't locate the class
throw new Exception('Class not found: ' . $class);
}
}
Upvotes: 2