Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoloading Traits in PHP

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';
  }
});
like image 766
savinger Avatar asked Feb 13 '13 05:02

savinger


1 Answers

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;
    }
});
like image 173
Phil Avatar answered Sep 27 '22 23:09

Phil