autoload functions in php

后端 未结 5 821
难免孤独
难免孤独 2020-12-07 03:35

Is it possible to autoload functions?

What I have is I have written functions distributed over different files named after the function name, so what I need is to au

相关标签:
5条回答
  • 2020-12-07 03:42

    You can autoload classes, so if you make your functions static methods of classes then it will work.

    abstract class Util
    {
        static function doSomething() {
    
        }
    }
    

    Usage:

    Util::doSomething();
    
    0 讨论(0)
  • 2020-12-07 03:47

    Nope, but you can load classes. using __autoload($className)

    0 讨论(0)
  • 2020-12-07 04:02

    Although this is not wise, it is possible.

    You may save those functions in a file and prepend this file to all requested scripts:

    • front controller pattern (one central file for all requests, include it there)
    • php's auto_prepend_file

    But the wise, OOP solution would be to group those functions into classes and use __autoload or some framework autoloader like Zend_Autloader to speed things up and load just the features you need.

    0 讨论(0)
  • 2020-12-07 04:07

    Use:

    include("path");
    

    or

    require_once("path");
    

    References:

    http://php.net/manual/en/function.include.php

    http://php.net/manual/en/function.require-once.php

    0 讨论(0)
  • 2020-12-07 04:07

    Not directly. But you can add following code to top of your code to automatically include functions:

    call_user_func(function($p,$w){$c=file_get_contents(__FILE__);$fs=explode('(',$c);$f=[];for($i=65;$i<=90;$i++){$vc[chr($i)]=1;$vc[chr($i+32)]=1;if($i<75)$vc[chr($i-17)]=1;}$vc['_']=1;foreach($fs as $fn){$fn=rtrim($fn);for($i=strlen($fn)-1;$i>=0;$i--){if(!isset($vc[$fn[$i]])){$f[]=substr($fn,$i+1);break;}}}foreach($f as $c){@include_once($p.$w[0].$c.$w[1]);}},
    "func_dir/",["func_",".php"]);
    

    The only thing you need to change is the second line: First parameter is the folder where to look for files, the second param is an array which wraps both values around the function name.

    For example: If your function files are in the sub directory "func_dir/" and are namen "func_*.php" (where * is the function name), then you can use the above code directly as-is. However, you have to put that code in every file where you want to load functions automatically and adapt the path.

    It's a little bit dirty, but it works. I hope my code helps you.

    0 讨论(0)
提交回复
热议问题