简体   繁体   English

用PHP自动加载特征

[英]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';
  }
});

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 您可以做的是在autoload堆栈中注册多个函数,一个用于处理类和其他特征,使用stream_resolve_include_path()或类似的东西,例如

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;
    }
});

There is a simple solution in the way you name your traits. 您的特征命名方式有一个简单的解决方案。 Every trait in my application is named trait_(name) and it is placed in the classes folder. 我的应用程序中的每个特征都命名为trait_(name),它放在classes文件夹中。

For example my trait_something is placed in the classes/ folder under the filename "trait.trait_something.php". 例如,我的trait_something放在文件名“trait.trait_something.php”下的classes /文件夹中。

My autoload function can pick up either the traits or the classes: 我的自动加载功能可以选择特征或类:

function autoloader($class) 
{
    $prefix='classes/';
    $ext='.php';
    if(substr($class,0,6) == 'trait_')include $prefix.'trait.' . $class . $ext; 
    else include $prefix.'class.' . $class . $ext;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM