PHP import functions

六月ゝ 毕业季﹏ 提交于 2019-12-06 11:29:13

One way you could pull something like this off is to put those functions into classes and then set up an __autoload function. If you are against wrapping the functions in classes than this solution probably won't apply to you. Personally I like it because it allows me to namespace my functions and share private methods between them.

First you set up your autoload function similar to this. You'll want to adjust the naming convention to fit your own style, and probably introduce some error handling, but this is just to get the basic idea across.

function __autoload($class_name){
     require_once(strtolower("library/$class_name.class.php"));
}

Then anywhere in your code regardless of scope you can do something like this.

arrayFunctions::doStuff($myArray);

PHP will automatically try to include "library/arrayFunctions.class.php" and look for a method called "doStuff" in the arrayFunctions class.

I have issues with this idea. Hitting the file system to include a single function is very expensive in the terms of it lowering your max possible requests per second.

It's generally much better to load/parse five functions in a single file (static class?) and only use two of them (one stat call) rather than load two files for two functions (two stat calls).

Which obviously becomes even worse when you need all five functions.

  1. To automatically load stuff when need, put your functions in classes and use autoloading.
  2. For the name conflict, use namespaces (if you have PHP 5.3).
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!