【问题标题】:'autoload' functions in php?php中的“自动加载”功能?
【发布时间】:2011-07-25 07:32:46
【问题描述】:

我有一个问题,我有很多巨大的功能,而我在给定的脚本中只使用了几个。 每个函数都位于自己的文件中。当给定函数不存在时,如果能够“自动加载”或者更确切地说需要一个文件,那就太好了。

也许有一种方法可以在脚本开头覆盖Fatal error: Call to undefined function...,因此每次启动该错误时,脚本都会首先尝试 require_once 一个具有不存在函数名称的文件名,然后尝试调用再次运行。

【问题讨论】:

标签: php


【解决方案1】:

由于 php 5.3.0 你可以这样做:

class Funcs
{
    public function __callStatic($name, $args) {
        if (!function_exists($name)) {
            require_once sprintf(
                'funcs/%s.func.php', // generate the correct path here
                $name
            );
        }

        if (function_exists($name)) {
            return call_user_func_array($name, $args);
        }
        else {
            // throw some error
        }
    }
}

然后像这样使用它(例如):

Funcs::helloworld();

这会尝试加载funcs/helloworld.func.php中的文件,加载成功后执行helloworld

这样你可以省略重复的内联测试。

【讨论】:

【解决方案2】:

function_exists

而且代码可能是这样的

if ( !function_exists('SOME_FUNCTION')) {
     include(.....)
 } 

【讨论】:

    【解决方案3】:

    如果你是在没有 OOP 的情况下编写脚本,你可以使用 function exists 函数:

    if(!function_exists('YOUR_FUNCTION_NAME')){
        //include the file
        require_once('function.header.file.php');
    }
    

    //现在调用函数

    //参考: http://php.net/manual/en/function.function-exists.php

    如果您正在使用类,例如。哎呀。比你可以使用 __autoload 方法:

    function __autoload($YOUR_CUSTOM_CLASS){
        include $YOUR_CUSTOM_CLASS.'class.php';
    }
    

    //现在您可以使用当前文件中未包含的类。

    //参考: http://php.net/manual/en/language.oop5.autoload.php

    【讨论】:

      【解决方案4】:

      function_exists 会做得更好

      【讨论】:

        【解决方案5】:

        我想你可以尝试编写一些包含 function_exists 的错误处理,但问题是确定何时加载该函数对吗?

        您是否考虑过将您的函数集成到类中以便利用 http://uk.php.net/autoload

        【讨论】:

          【解决方案6】:

          未定义的函数错误是 PHP 的致命错误。所以没有办法处理致命错误(除了像register_shutdown_function这样的黑客)。最好以 OOP 的方式思考并使用 __autoload 的类。

          【讨论】:

            【解决方案7】:

            function_exists 不会帮助您即时捕捉不存在的功能。相反,您必须用 if (!function_exists()) 包围所有函数调用。据我所知,您只能使用 _autoload 实现在运行中使用类来捕获不存在的调用。也许将您的代码放入类中或将相关的一组函数放入一个文件中,这样可以节省一些对 function_exists 所需的检查?

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-06-11
              • 1970-01-01
              • 1970-01-01
              • 2012-12-05
              • 1970-01-01
              • 1970-01-01
              • 2018-03-05
              • 2017-04-05
              相关资源
              最近更新 更多