Auto-load function / class libraries when needed

删除回忆录丶 提交于 2020-01-14 12:48:13

问题


First, a little background. The company I work for uses a massive function / class library, which gets included on every single page. Thousands and thousands of lines of functions, 90% of which probably won't even be called on a page.

In an attempt to lighten the server load a little, I've been experimenting with smarter library setups. To this end, I've split the entire file into categorized library files (i.e. sql.functions.php, date.functions.php, and others.)

Unfortunately, including every single file on every page doesn't help at all, and selectively including files is nearly impossible and very error-prone.

What I'm looking for is a setup similar to PHP's ___autoload() function, which automatically searches for specifically named files in case an unknown Class is initiated, in an attempt to find it.

<?php
  function ___autoload($class_name) {
    require_once($class_name.'.class.php');
  }
?>

However, this function does not work on function calls, only classes.

Is there a way to instruct PHP, when calling an undefined function (i.e. html_insert_button();), to automatically look for and include a named function library?

(In the above case, html_functions.php would need to be loaded, since it shares the function's prefix)


回答1:


I don't believe there is a way to autoload functions unfortunately. Some guys argued about this on the SitePoint forums.

I for one think it would be an awesome addition because it would let you reduce the amount of inlcudes.

I took this approach to loading my functions, very similar to CodeIgniter's:

Whenever I go to use a set of functions, I will call a library("html") function, that will include the library that I am about to use (making sure that it only includes it once).

function library($name)
{
    include($name .".lib.php");
}

Probably not the answer you are looking for, but that is how I do it.



来源:https://stackoverflow.com/questions/1208903/auto-load-function-class-libraries-when-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!