PHP自动加载功能

sos*_*iel 1 php function autoload

我想自动加载函数,而不是类.错误:

PHP致命错误:无法在第7行的/var/www/localhost/proba-function.php中重新声明proba()(之前在/var/www/localhost/proba-function.php:5中声明)

index.php代码:

class ASD {
    function __construct () {
        self::proba();
    }

    public static function __callStatic ( $name, $arguments ) {
        $foo = false;
        $directories = array_diff ( scandir ( __DIR__ ), array ( '..' ) );

        foreach ( $directories as $directory ) {
            $directory = __DIR__ . DIRECTORY_SEPARATOR . $directory;
            if ( is_dir ( $directory ) ) {
                $file = $directory . DIRECTORY_SEPARATOR . strtolower ( $name ) . '-function.php';
                if ( file_exists ( $file ) ) {
                    include ( $file ); // It's ok.
                    if ( function_exists ( $name ) ) {
                        $foo = true;
                        call_user_func_array(array('ASD', $name), $arguments); // It's not work.
                        break;
                    } else {}
                } else {}
            } else {}
        }

        if ( $foo === FALSE ) {
            $this -> error ( NULL, $name );
        } else {}
    }
}
Run Code Online (Sandbox Code Playgroud)

proba-function.php:

function proba () {
    print 'foo';
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ari 6

尝试更换您的include()呼叫include_once(),以便多次不包含相同的文件.

为了确保文件实际包含在内,也许您可​​以考虑使用require_once()而不是简单include_once().

另见文档:http://php.net/manual/en/function.include.php

  • 甚至可能是'require_once',因为这些函数似乎对应用程序至关重要. (2认同)