0

可能重复:
php中的自动加载函数

我正在开发一个 PHP 框架。我想知道是否有一种方法可以在函数不存在时重写错误处理程序以自动尝试首先包含说明该函数的文件。

例子:

echo general_foo(); // <-- general_foo() is not yet stated.
                    // A handler tries to include_once('functions/general.php') based on the first word of the function name.
                    // If the function still doesn't exist - throw an error.

这样做的好处是跳过编译不必要的文件或跳过跟踪和状态包括在这里和那里。

只需 __autoload 用于函数而不是类。

4

2 回答 2

1

它不存在,而且可能永远不会存在。是的,我也想要它……但是,这并不妨碍您使用具有静态函数的类并让 PHP 自动加载。

http://php.net/spl-autoload-register

于 2012-07-05T21:46:14.140 回答
-1

我这样解决了

类文件classes/functions.php:

  class functions {

    public function __call($function, $arguments) {

      if (!function_exists($function)) {
        $function_file = 'path/to/functions/' . substr($function, 0, strpos($function, '_')).'.php';
        include_once($function_file);
      }

      return call_user_func_array($function, $arguments);
    }
  }

函数文件functions/test.php

  function test_foo() {
    return 'bar';
  }

脚本 myscript.php:

  require_once('classes/functions.php');
  $functions = new functions();

  echo $functions->test_foo(); // Checks if function test_foo() exists,
                               // includes the function file if not included,
                               // and returns bar

您最终可以使用 __autoload() 自动加载 classes/functions.php。

最后,my_function() 的语法变成了 $functions->my_function()。如果函数不存在,您可以编写自己的错误处理程序。;)

于 2012-07-05T22:50:52.703 回答