需要时自动加载函数/类库
首先,介绍一下背景。 我工作的公司使用海量函数/类库,它包含在每个页面上。 成千上万行函数,其中 90% 甚至可能不会在页面上调用。
为了稍微减轻服务器负载,我一直在尝试更智能的库设置。 为此,我将整个文件分成分类库文件(即 sql.functions.php、date.functions.php 等)。
不幸的是,包含每个页面上的每个文件根本没有帮助,并且有选择地包含文件几乎是不可能的,而且很容易出错。
我正在寻找类似于 PHP 的 ___autoload()
函数的设置,该函数会在启动未知类的情况下自动搜索特定命名的文件,并尝试找到它。
<?php
function ___autoload($class_name) {
require_once($class_name.'.class.php');
}
?>
但是,该函数不适用于函数调用,仅适用于类。
有没有办法指示 PHP 在调用未定义函数(即 html_insert_button();
)时自动查找并包含命名函数库?
(在上述情况下,需要加载 html_functions.php
,因为它共享函数的前缀)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,我不相信有办法自动加载函数。 有些人在 SitePoint 论坛上对此进行了争论。
我认为这将是一个很棒的补充,因为它可以让你减少包含的数量。
我采用这种方法来加载我的函数,与 CodeIgniter 非常相似:
每当我要使用一组函数时,我都会调用一个库(“html”)函数,该函数将包含我将要使用的库(确保它只包含一次)。
可能不是您正在寻找的答案,但这就是我的做法。
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).
Probably not the answer you are looking for, but that is how I do it.