0

When using spl_autoload_register, an imported function via use function Namespace\Subamespace\aFunc php cannot find the function. The registered autolaod function is not invoked. If I manually include Path/To/File.php then the use statement works and the included function will work. Solutions?

autoload.php

function loader($class){
  printf("in loader");
  /*code to load file*/
}

spl_autoload_register('loader');

index.php

include_once('autoload.php');

use function Namespace\Subnamespace\aFunc;

$output = aFunc();

Namespace/Subnamespace.php

<?php namespace Namespace\Subnamespace;

function aFunc() {
  //do stuff
}
Cole
  • 119
  • 13
  • Does this answer your question? [use function doesn't import functions in PHP](https://stackoverflow.com/questions/51547511/use-function-doesnt-import-functions-in-php) – TimBrownlaw Sep 18 '20 at 21:05
  • I understand use doesn't import functions but I don't understand why my autoload function in autoload.php,using spl_autoload_register(), isn't been called even though I'm referencing the namespace and calling the function. – Cole Sep 19 '20 at 00:12
  • If you hunt around you will find that it does not work on functions. It only works for classes. So you will still have to include your function files. A workaround is to put your functions in a class and make them static (i.e. a singleton) and call them class::method. – TimBrownlaw Sep 19 '20 at 00:57
  • @TimBrownlaw yes that appears to be the case; autoloading only works with classes, traits, interfaces. Thanks for the clarification. – Cole Sep 19 '20 at 02:50
  • Does this answer your question? [Autoloader for functions](https://stackoverflow.com/questions/4737199/autoloader-for-functions) – rob006 Sep 19 '20 at 10:18

0 Answers0