Reputation: 13933
I've been looking around quite a bit and can't find a concise answer to this question anywhere- perhaps those of you with more experience autoloading than myself could shed some light. Pretty simple question:
I wrote a simple autoloader
:
function __autoload($className){
$className = BASEDIR . "include/class/" . str_replace("_", "/", $className) . ".php";
require_once($className);
}
Where BASEDIR
is the base project directory. Works great including classes- go figure.
However, when I go to include classes that extend other classes, it starts to break.
Per the suggestions on this site, I'm using PEAR
naming conventions for my classes. So my "Event" class (describing an actual event like a party) lives here:
include/class/Event/Event.php
The actual class name is "Event".
When autoloading the class, I reference it like so:
new Event_Event();
The autoloader turns that into:
"include/class/Event/Event.php";
The problem comes when Event
is extended by some other class utilizing this naming convention.
I'm using, for example:
class EventInstructed extends Event_Event
The autoloader knows where to look, but since my Event class name is "Event" and not "Event_Event", it is trying to look for the wrong class and can't find it.
The question therefore is, how do I utilize the pear naming conventions correctly, or should I do extra parsing in my autoloader to fix my issue? Explode the string on underscores, grab the class name and use that instead?
Naming conventions are here: http://pear.php.net/manual/en/standards.naming.php
Thanks!!
edit
My final solution was as mentioned in the accepted answer. Classes are in the hierarchy as such:
include/class/Event/Event.php
include/class/Event/Lesson.php // <-- extends Event
Inside the Event file:
abstract class Event_Event{
//Class code....
}
Inside the Lesson file:
class Event_Lesson extends Event_Event{
//Class code....
}
And finally, the __autoload function:
define("BASEDIR", __DIR__ . "/");
function __autoload($className){
$className = BASEDIR . "include/class/" . str_replace("_", "/", $className) . ".php";
echo $className . "<br / >";
require_once($className);
}
Upvotes: 0
Views: 675
Reputation: 1146
You should specify a namespace
... Like this:
namespace Event
{
abstract class Event {}
class Lesson extends Event {}
}
this shold work just fine with your autoload function.
P.S.: __autoload
function is deprecated. Try making this:
function Autoload ( $Subject )
{ /* ... */ }
spl_autoload_register('Autoload');
This way you'll not need the str_replace
in your Autoload
function...
You'll also be able to extend in other namespaces..
namespace OtherNamespace
{
class AnotherEvent extends Event\Event {}
}
Upvotes: 0
Reputation: 1275
You should always add the namespace like this:
class Event_Instructed extends Event_Event
The file name should be Instructed.php
in this case.
Upvotes: 1