Is there any way for me to differentiate between traits and classes in my autoload function? Say I have a folder of classes and a folder of traits; it would be nice to be able to do something like...
spl_autoload_register(function($resource) {
if ( /* $resource is class */ ) {
include 'classes/'.$resource.'.php';
}
if ( /* $resource is trait */ ) {
include 'traits/'.$resource.'.php';
}
});
The autoload callback function only receives one piece of information; the symbol name requested. There is no way to see what type of symbol it should be.
What you could do is register multiple functions in the autoload stack, one to handle classes and the other traits, using stream_resolve_include_path()
or something similar, eg
spl_autoload_register(function($className) {
$fileName = stream_resolve_include_path('classes/' . $className . '.php');
if ($fileName !== false) {
include $fileName;
}
});
spl_autoload_register(function($traitName) {
$fileName = stream_resolve_include_path('traits/' . $traitName . '.php');
if ($fileName !== false) {
include $fileName;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With