php 中的“自动加载”功能?

问题描述 投票:0回答:8

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

也许有办法在脚本开头覆盖

Fatal error:  Call to undefined function...
,因此每次引发错误时,脚本都会首先尝试 require_once 一个具有不存在函数名称的文件名,然后尝试再次调用该函数.

php
8个回答
4
投票

自 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
投票

函数存在

代码可能是这样的

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

1
投票

如果您在不使用OOP的情况下编写脚本,则可以使用函数exist函数:

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


0
投票

function_exists会做得更好


0
投票

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

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


0
投票

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


0
投票

function_exists 不会帮助您即时捕获不存在的函数。相反,您必须用 if (!function_exists()) 包围所有函数调用。据我所知,您只能使用 _autoload 实现即时捕获不存在的类调用。也许将代码放入类中或将相关的函数集放入一个文件中,从而节省对所需的 function_exists 的大量检查是有意义的?


0
投票

除了自动加载部分,我不明白为什么你不能只使用

require_once
? 许多人建议您在使用
function_exists
之前先使用
require_once
,但
require_once
的全部意义在于能够多次调用它,而不必先检查
function_exists
,对吗?

© www.soinside.com 2019 - 2024. All rights reserved.