rfc:autofunc

Request for Comments: Function autoloading through spl_autoload*

Introduction

The topic of supporting function autoloading was brought up many times in the past, this RFC introduces a potential implementation which would be consistent with what we have for autoloading classes.

Proposal

The suggested change would be pretty straightforward and BC compatible:

  • Add two new constants to spl: SPL_AUTOLOAD_CLASS, SPL_AUTOLOAD_FUNCTION.
  • Add a fourth optional parameter for spl_autoload_register called $types with the default value of SPL_AUTOLOAD_CLASS (this would keep the BC), supported values would be any combination of SPL_AUTOLOAD_CLASS and SPL_AUTOLOAD_FUNCTION for now.
    • As you would guess, this would work the same way as the $error_types parameter works for set_error_handler: you can specify for which type(s) of missing tokens the autoloader should be called.
  • The type for the missing token should also be passed to the $autoload_function callback as a second param.
    • This is needed to be able to handle multiple types of tokens with a common callback.
    • Note that passing more parameters to a function than it has in its definition is valid, this would also be a backward compatible change.
  • Change the current class autoloading to only call the autoloaders which match with the SPL_AUTOLOAD_CLASS types.
  • Add the function autoloading to only call the autoloaders which match with the SPL_AUTOLOAD_FUNCTION types.

Future improvements

Notice that currently only functions are proposed, but we could implement autoloading other tokens (SPL_AUTOLOAD_CONSTANT, etc.) with this interface.

Examples

 <?php
 // old behavior
 spl_autoload_register(
  function ($name) {
   // include the class definition
   /* ... */
  }
 );
 
 // autoload functions
 spl_autoload_register(
  function ($name) {
   // include the function definition
   /* ... */
  },
  true,
  false,
  SPL_AUTOLOAD_FUNCTION
 );
 
 // autoload mixed
 spl_autoload_register(
  function ($name, $type) {
   switch($type){
    case SPL_AUTOLOAD_CLASS:
     /* ... */
     break;
    case SPL_AUTOLOAD_FUNCTION:
     /* ... */
     break;      
   }
  },
  true,
  false,
  SPL_AUTOLOAD_CLASS|SPL_AUTOLOAD_FUNCTION
 );

Patch

Patches welcome! :)

Changelog

* 2011.08.17 - replace the T_* constants with SPL_AUTOLOAD_*

rfc/autofunc.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1