Autoloading functions best practices

可紊 提交于 2019-12-06 01:22:43

I wouldn't use 'Option 1' mostly because it uses call_user_func* which will be slower that calling function directly.

If you only need some helper functions that doesn't really tie together, then I would, probably, include a file helpers.php which would just have a list of all my helper functions which are not encapsulated in static class since encapsulation doesn't really achieve anything in this case. Most of the times helper functions will be used for every request so including this file on every request won't cause any harm...

I don't see a precise question here, but since the title contains "best practices", here's a piece of advice that I've recently discovered:

It seems to be preferable to use PHP's SPL autoload functions instead of __autoload() (nice example on "Dissection by David" blog).

Quoting the linked blog post:

The biggest benefits of using the SPL version (that I can see to-date) are:

  • more than one function can be used/registered — functions are chained together and used sequentially up to the point of one function loading the class file. + functions can be unregistered on-the-fly, too.
  • there is some nice error handling that can be implemented (see example 3), although some hat try/catch so this may not fit your coding style.
  • using a different extension (i.e. not .php or .php.inc or .inc) if you so choose with spl_autoload_extensions()
  • makes sure that ‘my’ autoloading class is not overwritten! If __autoload() is run later, my spl_autoload_register()’ed functions will not be replaced.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!